define(['moment','module/system/service/WatchDogService'], function (moment) {
    return ['$rootScope', '$state', '$scope', '$filter', '$stateParams', 'config', 'MMWService', '$mdDialog', '$timeout', '$interval', 'WatchDogService', 'RouterExtendProvider', '$mddProvider', 
    function ($rootScope, $state, $scope, $filter, $stateParams, config, $MMWService, $mdDialog, $timeout, $interval, $WatchDogService, $RouterExtendProvider, $mddProvider) {
        $scope.areaItem = {};     //現在選擇的生產區��?
        $scope.equipmentList = [];//區域內的機台列��?
        $scope.dashboard={};      //儀錶板物件
        $scope.machineItem = undefined;
        $scope.workLogFilterShow = {plot_no: false};
        $scope.workLogFilter = {plot_no:'', status:''};
        $scope.plot_list=[];//生產批陣列
        $scope.step_mode = 0; // 0 關閉掃描流程 | 1 設備 | 2 上工 | 3 下工 | 4 進站 | 5 出站
        let need_check = false;// 20231218 add by shiwl for M#0151498: 力邦合信，正式区。人员技能检核以后无记录写入数据库
        let check_member = '';//強制通過檢核人員 20201012 add by Oliver for M#78622
        //20210628 modify by kaiinagami for M#87684 - 煩請協助更新讓步程式[龍畿]
        //next_op_no參數獨立
        $scope.next_op_no = '';
        //$scope.plotItem = {};
        //20210511 Modify by德義家興for#84772
        $scope.workLogDetail = [];
        $scope.workLogTemp = [];
        //20210506 Modify by德義家興for#91011: [标准][DEV][行业议题]机加工-CNC-批量设备点检
        $scope.selectedEquipmentList = []; //勾選的設備列表
        $scope.options = undefined; //傳入B0210service的變數
        $scope.isPlugInEqualFive = false;
        $scope.plugin = '';
        // 20230328 add by 文蔚 for M#131657: SMES H5 一體化卡控調整，當子模塊編號OE_EMG為false的時候，需要隱藏今日生產任務的紅字功能
        $scope.OE_EMG = config.cache.module_setting.OE_EMG
        //20220923 add by 翰鴻 for M#118068
        $scope.plot_check_out_counter = 0; //M#91613 IIoT 出站通知筆數
        $scope.IIoT_Enable = false;
        $scope.init = function () {
            //20220916 add by 翰鴻 for M#118068
            if (
                $.grep(config.module, function (n, i) {
                    return n.name == "moduleIIoT"
                }).length > 0
            )
                $scope.IIoT_Enable = true;
            $scope.loginMin = 0;
            $scope.loginTime = config.cache.loginTime;
            caclLoginMin();
            //扣件行業包開啟參數
            $scope.isFastening = (config.cache.sys_parameter['FasteningPackage'] == '1' || config.cache.sys_parameter['FasteningPackage'] == 'Y');
            // 20230314 modify by Alan for#130010: 紧固件行业包卡控顯示雙單位
            $scope._event['production_info_detail.double_unit_qty'].isShown = $scope.isFastening ? 'Y' : 'N';
            $scope.employeeWorkReason = config.cache.sys_parameter.EmployeeWorkReason;
            $scope.feedingOpionOn = (config.cache.sys_parameter.MaterialFeedingOption == '1');
            $scope.GroupreportworkOption = (config.cache.sys_parameter['UCBModule'] == '1');
            $scope.IsInjectionMolding = (config.cache.sys_parameter.IsInjectionMolding == '1' ||
                                        config.cache.sys_parameter.IsInjectionMolding == 'Y' ||
                                        config.cache.sys_parameter.ISINJECTIONMOLDING == '1' ||
                                        config.cache.sys_parameter.ISINJECTIONMOLDING == 'Y'); // 注塑模組
            // 20230303 modify by Alan for#: module_setting卡控
            $scope.ESI_CLD = config.cache.module_setting && config.cache.module_setting.ESI_CLD;
            $mddProvider.UseForm('B0214', (formEntity)=>{
                if(formEntity){
                    $scope.$root.menuList = [];
                    formEntity.funcs.forEach(function(_func){
                        if(_func.funcPosition == 'ToolBar'){
                            let menuItem = {
                                name:_func.name,
                                title:_func.displayText,
                                icon:_func.icon,
                                isShow:_func.isShown != 'N',
                                order:_func.order,
                            };
                            // 20231020 modify by wenwei for M#148194: 厦晖：H5作业区工作平台，报工群组权限问题。
                            if (menuItem.name == 'B0235') menuItem.isShow = $scope.GroupreportworkOption;
                            if (menuItem.name == 'F0101') menuItem.isShow = $scope.feedingOpionOn;
                            if (menuItem.name == 'B0220') menuItem.isShow = !$scope.feedingOpionOn;

                            //20220916 add by 翰鴻 for M#118068
                            if ($scope.IIoT_Enable == false) {
                                if (menuItem.name == "IIoT0101" || menuItem.name == "IIoT0103") {
                                    menuItem.isShow = false;
                                }
                            }
                            if(!config.cache.permissions || config.cache.permissions.indexOf(menuItem.name)!=-1){
                                $scope.$root.menuList.push(menuItem);
                            }
                        }
                    });
                }
            });
            $scope.menuClick = function(item){
                var programName = item.name;
                if (programName == 'B0202') {
                    need_check = false;
                    //上工
                    var select_count = 0;
                    $scope.equipmentList.forEach(function(equipment)
                    {
                        if($scope.dashboard.machineStatusPlus.machineStatus[equipment.machine_no].isSelect)
                        {
                            select_count++;
                        }
                    });
                    has_lot_bind($scope.machineItem.machine_no,function(data)
                    {
                       if(data.page_number_info_get && data.page_number_info_get.length > 0)
                       {
                           var has_lot = data.page_number_info_get[0].lotbinding;
                           if(has_lot == "1" && select_count <= 1)
                            $mdDialog.serviceDialog('B0250Service',{mode_type:"U",lotInfoList:$scope.dashboard.workLog.production_info_detail,machineList: [$scope.machineItem], type: 'machine', parent: 'B0214'}, 
                            function()
                            {
                                dog.bark();
                            });
                            else
                            {
                                doWork('U');
                            }
                       }
                    });
                } else if (programName == 'B0203') {
                    //下工
                    var select_count = 0;
                    $scope.equipmentList.forEach(function(equipment)
                    {
                        if($scope.dashboard.machineStatusPlus.machineStatus[equipment.machine_no].isSelect)
                        {
                            select_count++;
                        }
                    });
                    has_lot_bind($scope.machineItem.machine_no,function(data)
                    {
                       if(data.page_number_info_get && data.page_number_info_get.length > 0)
                       {
                           var has_lot = data.page_number_info_get[0].lotbinding;
                           if(has_lot == "1" && select_count <= 1)
                            $mdDialog.serviceDialog('B0250Service',{mode_type:"D",lotInfoList:$scope.dashboard.workLog.production_info_detail,machineList: [$scope.machineItem], type: 'machine', parent: 'B0214'}, 
                            function()
                            {
                                dog.bark();
                            });
                            else
                            {
                                doWork('D');
                            }
                       }
                    });
                } else if (programName == 'B0210') {
                    //設備稼動
                    //20210506 Modify by德義家興for#91011: [标准][DEV][行业议题]机加工-CNC-批量设备点检
                    setSelectedEquipmentList();
                    // 20230322 Modify by 文蔚 for M#123460: 宁波全力机 3.4版本设备点检需要勾选设备
                    if ($scope.selectedEquipmentList.length == 0 && !$scope.dashboard.machineStatusPlus.selectMachine.machine_no) {
                        $scope.$root.showAlert($filter('translate')('B0210.msg.please_select_at_least_one_equipment'));
                    }else{
                        $mdDialog.serviceDialog('B0210Service', $scope.options, $scope.selectedEquipmentList, function(){
                            dog.bark();
                        });
                    }
                } else if (programName == 'B0211') {
                    //設備點檢
                    $scope.machineItem.status = $scope.machineItem.machine_status;
                    $mdDialog.serviceDialog('B0211Service', $scope.machineItem, function(){
                        dog.bark();
                    });
                } else if (programName == 'B0220') {
                     //下料
                     $scope.$root.getService('B0220Service', function($B0220Service){
                        $B0220Service.trenching($scope.machineItem.machine_no, function(){
                            dog.bark();
                        });
                    });
                } else if (programName == 'B0221') {
                    //20221012 add by 翰鴻 for M#118366
                    var proList = new Set();
                    $.each($scope.dashboard.workLog.production_info_detail, function (index, obj) {
                        if (obj.status == 'R' || obj.status == 'Q' || obj.status == 'W')
                            proList.add(obj.item_no);
                    });
                    //機台上下具作��?
                    $mdDialog.serviceDialog('B0221Service', {
                        parent: "B0214",
                        machine : $scope.machineItem,
                        ProductList: Array.from(proList),
                        callback: function () {
                            dog.bark();
                        }
                    });
                } else if (programName == 'F0101') {
                    //物料管理
                    $mdDialog.serviceDialog('F0101Service',{
                        parent: 'B0214',
                        lot_no: $scope.plotItem.plot_no,//20210507 modify by 德義_林佳諺 for #0086310 檢查PlugIn需要之參數
                        machine_no: $scope.machineItem.machine_no,
                        check_dispatch_machine: $scope.machineItem.check_dispatch_machine,  // 20231103 modify by Alan for#0149409 : 是否為派工設備
                        callback : function(){
                            dog.bark();
                        }
                    });
                } else if (programName == 'B0235') { //群组报工
                    var tempEquipmentList = [];
                    $scope.equipmentList.forEach(function (equipment) {
                        if ($scope.dashboard.machineStatusPlus.machineStatus[equipment.machine_no].isSelect) {
                            tempEquipmentList.push(equipment);
                        }
                    });
                    if (tempEquipmentList.length == 0) {
                        tempEquipmentList.push($scope.machineItem);
                    }

                    $mdDialog.serviceDialog('B0235Service', tempEquipmentList, 'machine', 'B0214', function () {
                        dog.bark();
                    });
                }
                //20221004 add by 翰鴻 for M#118068
                //IIoT 任務進度
                else if ($scope.IIoT_Enable && programName == 'IIoT0101') {
                    $mdDialog.serviceDialog('IIoT0101_Service', {
                        parent: 'B0214',
                        equipment_no: $scope.machineItem.machine_no,
                        feedback: function (dialog) {
                            dialog.hide();
                            dog.bark();
                        }
                    });
                }
                //IIoT 出站通知
                else if ($scope.IIoT_Enable && programName == 'IIoT0103') {
                    var options = {};
                    options.equipment_no = $scope.machineItem.machine_no;
                    options.area_no = $scope.machineItem.area_no;
                    options.parent = "B0214";
                    options.feedback = function (dialog) {
                        dog.bark();
                        dialog.hide();
                    }
                    $mdDialog.serviceDialog('IIoT0103_Service', options);
                }
            };
            /**Slight**/
            $scope.slight_details = $RouterExtendProvider.slight_details;

            $scope.dashboard = {
                operatorInfo : {
                    templateUrl : 'module/moduleB/program/dashboard/operatorInfo.html'
                },
                machineStatusPlus: {
                    templateUrl : 'module/moduleB/program/B02/B0214/B0214_MachineStatusPlus.html',
                    machineStatus:{}
                },
                productInfo: {
                    templateUrl : 'module/moduleB/program/B02/B0214/B0214_ProductInfo.html',
                },
                workMaterial: {
                    templateUrl : 'module/moduleB/program/dashboard/workMaterial.html'
                },
                workMaterialOp: {
                    templateUrl : 'module/moduleB/program/dashboard/workMaterialOp.html'
                },
                workLog : {
                    templateUrl : 'module/moduleB/program/B02/B0214/B0214_WorkLog.html',
                    statusList : ['Q', 'R', 'W', 'C', 'O', 'I']
                },
                accessory : {
                    templateUrl : 'module/moduleB/program/dashboard/accessory.html'
                },
                dashboard_info : {
                    templateUrl : 'module/moduleB/program/dashboard/dashboard_info.html',
                    isContentHide:true,
                    isForceHide:false,
                    rate_detail:[]
                },
                slightModuleInfo: { // 安燈按鈕模塊
                    templateUrl: '',
                }
            };

            // 20230303 modify by Alan for#: module_setting卡控
            if($scope.ESI_CLD) {
                $scope.dashboard.countInfo = {
                    templateUrl : 'module/moduleB/program/dashboard/countInfo.html'
                }
            }

            // 20220615 modify by Alan for#100246: 修正安燈不顯示的問題
            $scope.slightModule = config.cache.sys_parameter["SlightModule"]; // 安燈模組權限
            if ($scope.slightModule && $scope.slightModule === '1') {
                // 有啟動安燈模組時，operatorInfo 模塊的畫面排版方式需要調整
                $scope.dashboard.operatorInfo.templateUrl = 'module/moduleMSG/program/dashboard/operatorInfo.html';
                $scope.dashboard.slightModuleInfo.templateUrl = 'module/moduleMSG/program/dashboard/slightModuleInfo.html';
                $scope.slightModuleCss = 'slightModuleCss';
                $scope.dashboardPanel.push('slightModuleInfo');
            }

            $scope.userInfo = {shift_desc:''};
            if (typeof(Storage) !== 'undefined') {
                var panel_setting = JSON.parse(localStorage.getItem(config.appName + '_B0214_panel'));
                if(panel_setting){
                    // 20230303 modify by Alan for#: module_setting卡控
                    // 檢查保存在local stroage的設定，有權限才套用
                    var pass = true;
                    if(pass && panel_setting.includes('slightModuleInfo')){
                        pass = ($scope.slightModule && $scope.slightModule === '1');
                    }
                    if(pass && panel_setting.includes('workMaterialOp')){
                        pass = $scope.feedingOpionOn;
                    }
                    if(pass && panel_setting.includes('countInfo')){
                        pass = $scope.ESI_CLD;
                    }
                    if(pass) {
                        $scope.dashboardPanel = panel_setting;
                    }
                }
            }

            $scope.$root.getService('B0222Service', function($B0222Service){
                $B0222Service.init($scope)
            });

            $scope.PageConfig = {
                page : 0,
                page_count : 25
            };

            $scope.workLogOrder = {}; //生產任務排序物件
            //使用user.infomation.get取得使用者資��?
            user_infomation_get(function(){
                setMachineList($stateParams.machine_list);
                machine_working_info_get('1011', function(){
                    $WatchDogService.startWatch(dog, true);
                });
            });

            count_info_get(function(feedback, isShowLoading){
                count_info_dog = $timeout(function(){
                    count_info_get(feedback, false);
                }, 1000);
            }, true);
            if (angular.fromJson(localStorage[config.appName + "_B0214_workLogStatusList"])) {
                $scope.dashboard['workLog'].statusList = [];
                angular.fromJson(localStorage[config.appName + "_B0214_workLogStatusList"]).forEach(function(temp) {
                    $scope.dashboard['workLog'].statusList.push(temp);
                });
            };
        };

        //20220311 add by 翰鴻 for M#102608
        function in_order_check(content, callback){
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_WIP.trackout_in_order_check_info_get',
                content: content,
                success: function (data, response) {
                    if (data.forceCheck) {
                        $rootScope.showConfirm($filter('translate')('B0214.msg.in_order_or_force'), function (confirmDialog) {
                            confirmDialog.hide();
                            $mdDialog.serviceDialog('PasswordService', {
                                mode: 'AreaLeader',
                                equipmentno: content.EquipmentNo,
                                feedback: function () {
                                    if (callback)
                                        callback();
                                }
                            });
                        });
                    }
                    else
                    {
                        if (callback)
                            callback();
                    }
                }
            });            
        }

        //20221004 add by 翰鴻 for M#118068
        //M#91613 [IIoT] 添加查詢出站通知筆數
        function get_eqp_prod_count(machine_no, isShowLoading, callback) {
            var content = {};
            content.page_mode = "3T_EQP_PROD_COUNT";
            content.query_condition_info =
                [{ column_name: "EQUIPMENTNO", value: machine_no, query_mode: "0", merge_condition_model: "AND" }];
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_SYS.page_number_info_get',
                content: content,
                success: function (data) {
                    if (callback)
                        callback(data);
                }
            }, isShowLoading);
        };

        function has_lot_bind(machine_no,callback){
            var content = {};
            content.page_mode = "has_lot_bind_info";
            content.query_condition_info = 
            [{column_name:"EQUIPMENTNO",value:machine_no,query_mode: "0",merge_condition_model: "AND"}];
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_SYS.page_number_info_get',
                content : content,
                success : function(data)
                {
                    if (callback)
                        callback(data);
                }
            });
        }

        function setMachineList(machine_list){
            machine_list.forEach(function(machine){
                if(!$scope.dashboard.machineStatusPlus.machineStatus[machine.machine_no])
                    $scope.dashboard.machineStatusPlus.machineStatus[machine.machine_no] = {isSelect:false};
            });
            $scope.dashboard.machineStatusPlus.machineList   = $stateParams.machine_list = $scope.equipmentList = machine_list;
            $state.$current.locals.globals.$stateParams.machine_list = machine_list;

            if(!$scope.dashboard.machineStatusPlus.selectMachine){
                $scope.machineItem = $scope.equipmentList[0];
                $scope.dashboard.machineStatusPlus.selectMachine = $scope.machineItem;
            }
        }

        $scope.back = function(){
            $scope.disconnection = false;
            $scope.final(function(){
                $scope.$root.changeProgram('home', true);
            });
        };

        $scope.final = function(callback){
            if(displayLoginMin){
                $interval.cancel(displayLoginMin);
            }
            if(refresh_timer != undefined){
                $timeout.cancel(refresh_timer);
                refresh_timer = undefined;
            }
            if(count_info_dog != undefined){
                $timeout.cancel(count_info_dog);
                count_info_dog = undefined;
            }
            $WatchDogService.stopWatch();
            if(typeof callback === 'function')
                callback();
        }

        //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
        var refresh_timer;
        function ErrorHandler(msg, isShowLoading, callback){
            if($scope){
                $scope.$root.showAlert(msg);
                if(!isShowLoading){
                    $scope.disconnection = true;
                    $scope.refresh =  function(){
                        $scope.disconnection = false;
                        $timeout.cancel(refresh_timer);
                        refresh_timer = undefined;
                        callback();
                    };
                    if(refresh_timer == undefined){
                        refresh_timer = $timeout(function(){
                            $scope.refresh();
                        }, config.setting.RefreshTime*1000);
                    }
                }
            }
        }

        //使用user.infomation.get取得使用者資��?
        function user_infomation_get(feedback, isShowLoading){
            $MMWService.sendToServer({
                uri : 'ServicesSTD.Module_SYS.user_information_get',
                content : {
                    employee_no : config.cache.account,
                    report_datetime:moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
                    machine_no:'A',
                    return_type : '00'
                },
                success : function(data){
                    $scope.userInfo = angular.merge($scope.userInfo, data);
                    $scope.userInfo.start_date = data.shift_start_date;
                    $scope.userInfo.end_date = data.shift_end_date;
                    if(feedback)
                        feedback();
                },
                error: function(data){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一��?
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(data.Message, isShowLoading, function(){
                        user_infomation_get(feedback, isShowLoading);
                    });
                },
                netError: function(msg){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一��?
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(msg, isShowLoading, function(){
                        user_infomation_get(feedback, isShowLoading);
                    });
                }
            }, isShowLoading);
        }

        //我的最愛機台資訊取��?
        function favourite_machine_info_get(feedback, isShowLoading) {
            var content = {
                master_no:config.cache.account,
                master_type:'0',
                get_employee_data:'Y'
            };
            $MMWService.sendToServer({
                uri : 'ServicesSTD.Module_SYS.favourite_machine_info_get',
                content : content,
                success : function(data){
                    //根據第一筆機台取出設備加工資��?
                    // if(data.favourite_machine_info_get.length > 0){
                    if(data.query_restult.length > 0){

                        // setMachineList(data.favourite_machine_info_get);
                        setMachineList(data.query_restult);
                        if(!checkMachine()){
                            $scope.machineItem = $scope.equipmentList[0];
                            $scope.dashboard.machineStatusPlus.selectMachine = $scope.machineItem;
                        }
                        machine_working_info_get('1011', feedback, isShowLoading);
                    } else if(feedback){
                        feedback();
                    }
                },
                error: function(data){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一��?
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(data.Message, isShowLoading, function(){
                        favourite_machine_info_get(feedback, isShowLoading);
                    });
                },
                netError: function(msg){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一��?
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(msg, isShowLoading, function(){
                        favourite_machine_info_get(feedback, isShowLoading);
                    });
                }
            }, isShowLoading);
        }

        //判斷機台是否有在我的最愛機台列表裡��?
        function checkMachine(){
            var isIn = false;
            $scope.dashboard.machineStatusPlus.machineList.forEach(function(machine){
                if($scope.machineItem.machine_no == machine.machine_no){
                    $scope.machineItem = machine;
                    isIn = true;
                }
            });

            return isIn;
        }

        //設備加工資訊取得
        function machine_working_info_get(data_type, feedback, isShowLoading)  {
            var content = {
                machine_no: $scope.machineItem.machine_no,
                data_type : data_type
            };

            // 20180518 modify by 李栋 for mantis#0046663
            $MMWService.sendToServer({
                uri : 'ServicesSTD.Module_EQP.machine_working_info_get',
                content : content,
                success : function(data){
                    if(data.shift_desc.length>0){
                        $scope.userInfo.shift_desc = data.shift_desc.substring(0,1);
                    } else {
                        $scope.userInfo.shift_desc = '';
                    }
                    $scope.dashboard.workLog.production_info_detail = data.machine_production_info_detail; //今日生產任務

                    // 20210828 modify by chenshibo for#98846：改为从后端取，前端没必要在forEach了
                    ////20210511 Modify by德義家興for#84772
                    //$scope.dashboard.workLog.production_info_detail.forEach(function (item) {
                    //    if (item.status == 'C') {
                    //        //getPlotV_CONTS(item, content.machine_no);//取得每日生產任務;當日同一生產批出站的次數
                    //        // 20210828 modify by chenshibo for#98846：频繁调用后端服务有很大效能问题，已经取出来直接计算就好，没必要再去数据库查询
                    //        var templist = $scope.dashboard.workLog.production_info_detail.filter(function (plotItem) {
                    //            return plotItem.op_no == item.op_no && plotItem.plot_no == item.plot_no && plotItem.status == 'C';
                    //        });
                    //        item.v_conts = templist.length;
                    //    }
                    //})
                    getWorkLogPlotDetail(content.machine_no)//取得每日生產任務;已出站生產批的資訊

                    //$scope.dashboard.productInfo = angular.merge($scope.dashboard.productInfo, data.machine_production_history_info_detail[0]);    //生產資訊
                    $scope.dashboard.workMaterial.materials_detail = data.machine_materials_detail;  //上料資訊
andon_eqp_status_info_get(); // 取得安燈按鈕
                    //設備集成
                    /*
                    $scope.dashboard.dashboard_info.update_time = data.param_update_time;//為null則表示沒有設定設備集成
                    $scope.dashboard.dashboard_info.counter = data.current_count;

                    $scope.dashboard.dashboard_info.rate_detail = data.machine_param_detail;

                    */
                    // 20231123 modify by wenwei for M#137875: iiot 计数器 
                    let all_param_type_equal_N =  data.machine_param_detail.every(item => item.param_type == 'N')
                    // 20190701 modify by Dustdusk for M#: 不會每次都跳出來
                    if(!$scope.dashboard.dashboard_info.isForceHide){
                        // 20230303 modify by Alan for#: module_setting卡控
                        if(data.machine_param_detail.length > 0 && $scope.ESI_CLD && !all_param_type_equal_N){
                            $scope.dashboard.dashboard_info.isContentHide = false;
                        } else {
                            $scope.dashboard.dashboard_info.isContentHide = true;
                        }
                    }
                    try{
                        //$scope.$root.loadMenu();
                        machine_accessory_map_get(feedback, isShowLoading);
                    }catch(e){console.log(e);}
                },
                error: function(data){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一��?
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(data.Message, isShowLoading, function(){
                        machine_working_info_get(data_type, feedback, isShowLoading);
                    });
                },
                netError: function(msg){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一��?
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(msg, isShowLoading, function(){
                        machine_working_info_get(data_type, feedback, isShowLoading);
                    });
                }
            }, isShowLoading);
        }

        // 取得安燈按鈕
        function andon_eqp_status_info_get() {
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_MSG.andon_eqp_status_info_get',
                content: {
                    equipment_no: $scope.machineItem.machine_no
                },
                success: function (data) {
                    if (data.andon_data && data.andon_data.length > 0) {
                        $scope.andon_min_time = data.andon_min_time || ''; // 安燈時間
                        $scope.andon_data = data.andon_data; // 安燈按鈕資訊
                    }
                }
            });
        }

        // 取得安燈按鈕顏色
        // 20220729 modify by Alan for#100246 : 配合現有樣式調整安燈面板預設顏色
        $scope.getSlightColor = function (item) {
            // 後台回傳色碼為 N/A 時，要自行判斷，剩下可以在車間調色盤設定，直接由後台帶回來
            if (item.slight_colour === 'N/A') {
                if (item.slight_status === '4') { // 4: 藍色
                    return { background: '#1ab7cd' };
                } else if (item.slight_status === '1' || item.slight_status === '2' || item.slight_status === '3') { // 1、2、3: 紅色
                    return { background: '#DD4264' };
                } else { // 0 : 綠色
                    return { background: '#91D472' }; // 預設綠色
                }
            } else {
                return { background: item.slight_colour }; // 後台直接帶色碼回來
            }
        }

        // 執行點擊的安燈按鈕 -> 請搭配 SA 規格查看
        $scope.slightBtn = function (item) {
            if (item.slight_status === '0') {
                if (!item.write_info) { // 0
                    onePointOneSlight(item); // 安燈邏輯 1.1
                } else { // 1
                    onePointTwoSlight(item); // 安燈邏輯 1.2
                }
            } else if (item.slight_status === '1') {
                if (!item.receive_project) { // 0
                    if (!item.write_start) { // 0
                        fiveSlight(item); // 安燈邏輯 5
                    } else { // 1
                        fourSlight(item); // 安燈邏輯 4
                    }
                } else { // 1
                    twoSlight(item); // 安燈邏輯 2
                }
            } else if (item.slight_status === '2') {
                threeSlight(item); // 安燈邏輯 3
            } else if (item.slight_status === '3') {
                fiveSlight(item); // 安燈邏輯 5
            } else if (item.slight_status === '4') {
                sevenSlight(item); // 安燈邏輯 7
            } else {
                // 查無此安燈邏輯，請重新確認
                $scope.$root.showAlert($filter('translate')('B0214.slightMsg.column3'));
            }
        }

        function machine_accessory_map_get(feedback, isShowLoading) {
            var content = {
                machine_no: $scope.machineItem.machine_no,
                is_line: '0'
            };

            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_ACC.machine_accessory_map_get',
                content : content,
                success : function(data){
                    $scope.dashboard.accessory.accessory_detail = data.accessory_detail;
                    try{
                        checkLotInfo(feedback, isShowLoading);
                    }catch(e){ console.error(e);}
                },
                error: function(data){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一��?
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(data.Message, isShowLoading, function(){
                        machine_accessory_map_get(feedback, isShowLoading);
                    });
                },
                netError: function(msg){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一��?
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(msg, isShowLoading, function(){
                        machine_accessory_map_get(feedback, isShowLoading);
                    });
                }
            }, isShowLoading);
        }

        // 安燈邏輯 1.1
        function onePointOneSlight(item) {
            var content = {
                slight_status: item.slight_status, // 安燈狀態
                write_info: item.write_info, // 是否側錄安燈訊息選項 -> 0 : 否 ; 1 : 是
                write_start: item.write_start, // 是否處理安燈任務開始時間選項 -> 0 : 否 ; 1 : 是
                receive_project: item.receive_project, // 是否必須接受安燈任務選項 -> 0 : 否 ; 1 : 是
                //20210423 Modify by德義家興for#78800: [标准][安灯/讯息][DEV]安灯与设备稼动联动机制
                change_eqp_status: item.change_eqp_status, //安灯时是否同步改变设备状态  0 = 否 1 = 是
                eqp_status: item.eqp_status, //0-7对应安灯后设备将要修改成的状态     
                // 20220621 add by zhuyc0412 for#0100246: [3.4.1patch][安灯]安灯模块相关优化建议及相关议题搬迁
                eqp_process_status: item.eqp_process_status,//0-7对应安灯后设备将要修改成的状态     
                eqp_status_back: item.eqp_status_back, //0-否 1-是 安灯处理流程结束后是否自动将设备状态还原至安灯前
                eqp_status_list: [ // 每個安燈邏輯帶入的資料都不同
                    {
                        equipment_no: $scope.machineItem.machine_no,
                        slight_type_no: item.slight_type_no
                    }
                ]
            };

            // 安燈寫入
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_MSG.andon_eqp_status_process',
                content: content,
                success: function () {
                    andon_eqp_status_info_get(); // 刷新安燈按鈕
                    //20210423 Modify by德義家興for#78800: [标准][安灯/讯息][DEV]安灯与设备稼动联动机制
                    dog.bark(); // 刷新設備資訊
                }
            });
        }

        // 安燈邏輯 1.2
        function onePointTwoSlight(item) {
            $mdDialog.serviceDialog(
                'Andon00Service',
                item,
                $scope.machineItem.machine_no,
                function () {
                    andon_eqp_status_info_get(); // 刷新安燈按鈕
                    //20210423 Modify by德義家興for#78800: [标准][安灯/讯息][DEV]安灯与设备稼动联动机制
                    dog.bark(); // 刷新設備資訊
                }
            );
        }

        // 安燈邏輯 2
        function twoSlight(item) {
            if (item.slight_status === '2' && item.receiver) {
                let newItem = angular.copy(item);
                $MMWService.pageNumberInfoGet({
                    page_mode: 'andon_eqp_status_get',
                    query_condition_info: [
                        { column_name: 'SLightTypeNo', query_mode: '0', value: item.slight_type_no, merge_condition_model: 'AND' },
                        { column_name: 'EquipmentNo', query_mode: '0', value: $scope.machineItem.machine_no, merge_condition_model: 'AND' }
                    ]
                }, function (itemList) {
                    if (itemList && itemList.length > 0) {
                        newItem.slight_status = itemList[0].slightstate;
                        newItem.receiver = itemList[0].receiver;
                        threeSlight(newItem);
                    } else {
                        // 查無安燈狀態
                        $scope.$root.showAlert($filter('translate')('B0214.slightMsg.column2'));
                    }
                });
            } else {
                // 該安燈任務需要相應人員接受後才可以繼續後續流程
                $scope.$root.showAlert($filter('translate')('B0214.slightMsg.column1'));
            }
        }

        // 安燈邏輯 3
        function threeSlight(item) {
            if (!item.write_start) { // 0
                fiveSlight(item); // 安燈邏輯 5
            } else { // 1
                fourSlight(item); // 安燈邏輯 4
            }
        }

        // 安燈邏輯 4
        function fourSlight(item) {
            $mdDialog.serviceDialog(
                'Andon02Service',
                item,
                $scope.machineItem.machine_no,
                function () {
                    andon_eqp_status_info_get(); // 刷新安燈按鈕
                     // 20220621 add by zhuyc0412 for#0100246: [3.4.1patch][安灯]安灯模块相关优化建议及相关议题搬迁
                    dog.bark(); // 刷新設備資訊
                }
            );
        }

        // 安燈邏輯 5
        function fiveSlight(item) {
            $mdDialog.serviceDialog(
                'Andon01Service',
                item,
                $scope.machineItem.machine_no,
                function () {
                    andon_eqp_status_info_get(); // 刷新安燈按鈕
                     // 20220621 add by zhuyc0412 for#0100246: [3.4.1patch][安灯]安灯模块相关优化建议及相关议题搬迁
                    dog.bark(); // 刷新設備資訊
                }
            );
        }

        // 安燈邏輯 7
        function sevenSlight(item) {
            $mdDialog.serviceDialog(
                'Andon03Service',
                item,
                $scope.machineItem.machine_no,
                function () {
                    andon_eqp_status_info_get(); // 刷新安燈按鈕
                    //20210423 Modify by德義家興for#78800: [标准][安灯/讯息][DEV]安灯与设备稼动联动机制
                    dog.bark(); // 刷新設備資訊
                }
            );
        }

        /*取得設備集成資訊*/
        var count_info_dog;
        function count_info_get(feedback, isShowLoading) {
            if (($scope.machineItem != undefined && $scope.dashboardPanel.includes('countInfo'))
                || (!$scope.dashboard.dashboard_info.isForceHide && !$scope.dashboard.dashboard_info.isContentHide)) {
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_EQP.machine_working_info_get',
                    content: {
                        machine_no: $scope.machineItem.machine_no,
                        data_type: '0000'
                    },
                    success: function (data) {
                        //設備集成
                        //20201223 3.2.2.DEV.2020122301 M#0079362:[標準][本土][IIOT] [DEV]計數器顯示增列上次出站數量
                        if (data.param_update_time !== null && data.param_update_time != undefined) {  //出站紀錄
                            $scope.dashboard.dashboard_info.update_time = moment(data.param_update_time).format('YYYY-MM-DD HH:mm');
                        } else {
                            $scope.dashboard.dashboard_info.update_time = "";
                        }
                        if (parseInt(data.current_count) > 0) { //當前計數量
                            $scope.dashboard.dashboard_info.current_count = parseInt(data.current_count);
                        } else {
                            $scope.dashboard.dashboard_info.current_count = 0;
                        }
                        if (data.counter_pre != "" && data.counter_pre !== null && data.counter_pre != undefined) { //前次出站計數量
                            $scope.dashboard.dashboard_info.counter_pre = parseInt(data.counter_pre);
                        } else {
                            $scope.dashboard.dashboard_info.counter_pre = 0;
                        }
                        if (data.counter != "" && data.counter !== null && data.counter != undefined) { //計數總量
                            $scope.dashboard.dashboard_info.counter = parseInt(data.counter);
                        } else {
                            $scope.dashboard.dashboard_info.counter = 0;
                        }
                        $scope.dashboard.dashboard_info.rate_detail = data.machine_param_detail;
                        //20220923 add by 翰鴻 for M#118068
                        //IIoT M#91511 計數器上生產批資料
                        if ($scope.IIoT_Enable) {
                            $scope.dashboard.dashboard_info.machine_no = $scope.machineItem.machine_no;
                            $scope.dashboard.dashboard_info.counter_equipment = [];
                            if (data.counter_equipment) {
                                data.counter_equipment.forEach(function (c_item) {
                                    var obj = {};
                                    obj.item_title = c_item.lot_no + "：";
                                    obj.item_content = Math.round(c_item.accQty) + "/" + Math.round(c_item.lot_total_qty);
                                    $scope.dashboard.dashboard_info.counter_equipment.push(obj);
                                });
                            }
                            //IIoT 出站通知更新
                            if ($scope.machineItem && $scope.machineItem.machine_no) {
                                get_eqp_prod_count($scope.machineItem.machine_no, false, function (data) {
                                    if (data.page_number_info_get && data.page_number_info_get.length > 0) {
                                        $scope.plot_check_out_counter = data.page_number_info_get[0].cnt;
                                    }
                                })
                            }
                        }
                        // 20231123 modify by wenwei for M#137875: iiot 计数器 
                        let all_param_type_equal_N =  $scope.dashboard.dashboard_info.rate_detail.every(item => item.param_type == 'N')
                        // 20190701 modify by Dustdusk for M#: 不會每次都跳出來
                        if (!$scope.dashboard.dashboard_info.isForceHide) {
                            if ($scope.dashboard.dashboard_info.rate_detail.length > 0 && !all_param_type_equal_N) {
                                $scope.dashboard.dashboard_info.isContentHide = false;
                            } else {
                                $scope.dashboard.dashboard_info.isContentHide = true;
                            }
                        }
                        try {
                            feedback(feedback, isShowLoading);
                        } catch (e) { console.log(e); }
                    },
                    error: function (data) {
                        //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一次
                        //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                        console.error(data.Message);
                        feedback(feedback, isShowLoading);
                    },
                    netError: function (msg) {
                        //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一次
                        //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                        console.error(msg);
                        feedback(feedback, isShowLoading);
                    }
                }, isShowLoading);
            } else {
                feedback(feedback, isShowLoading);
            }
        }

        function checkLotInfo(callback, isShowLoading){
            if($scope.dashboard.workLog.production_info_detail.length > 0){
                if(!$scope.plotItem){
                    $scope.plotItem = $scope.dashboard.workLog.production_info_detail[0];
                }
                lotinfo_get($scope.plotItem, callback, isShowLoading);
            } else {
                $scope.dashboard.productInfo.item_code = '';
                $scope.dashboard.productInfo.product_name = ''; // 20230503 add by Alan for M#: 產品名稱未清空
                $scope.dashboard.productInfo.wo_no = '';
                $scope.dashboard.productInfo.plot_no = '';
                $scope.dashboard.productInfo.qty = '';
                $scope.dashboard.productInfo.OutputQty = '';
                $scope.dashboard.productInfo.ScrapQty = '';
                $scope.dashboard.productInfo.GoodQty = '';
                $scope.dashboard.productInfo.reached_rate = '';
                $scope.dashboard.productInfo.next_op_no = '';
                $scope.dashboard.productInfo.flow_chart_url = '';
                if(callback)
                    callback();
            }
        }
        var reload_time = 0;
        function lotinfo_get(plotItem, callback, isShowLoading){
            var content = {
                LotNo : plotItem.plot_no,
                OPNo : plotItem.op_no,
                Status: plotItem.status,
                machine_no: $scope.machineItem.machine_no
            };
            $MMWService.sendToServer({
                uri : 'ServicesSTD.Module_WIP.plot_display_info_get',
                content : content,
                success : function(data){
                    reload_time = 0; //清除取得紀��?
                    $scope.dashboard.productInfo.item_code = data.ProductNo;
                    $scope.dashboard.productInfo.wo_no = data.MONo;
                    $scope.dashboard.productInfo.product_name = data.ProductName;//產品名稱
                    $scope.dashboard.productInfo.plot_no = data.LotNo;
                    $scope.dashboard.productInfo.qty = data.CurQTY;
                    $scope.dashboard.productInfo.OutputQty = data.OutputQty;
                    $scope.dashboard.productInfo.ScrapQty = data.ScrapQty;
                    $scope.dashboard.productInfo.GoodQty = data.GoodQty;
                    $scope.dashboard.productInfo.reached_rate = data.TodayArriveRate + '%';
                    //20210611 modify by kaiinagami for M#87684 - $scope.plotItem增加next_op_no, 使B0209可以判斷末站
                    $scope.dashboard.productInfo.next_op_no = data.next_op_no;
                    //20210628 modify by kaiinagami for M#87684 - 煩請協助更新讓步程式[龍畿]
                    //next_op_no參數獨立
                    $scope.next_op_no = data.next_op_no;
                    $scope.dashboard.productInfo.flow_chart_url = data.flow_chart_url;
                    //20230322 modify by ShengKun for M# 121894: 序列號檢驗優化
                    $scope.dashboard.productInfo.NeedSN = data.NeedSN;
                    if(callback)
                        callback();
                },
                error: function(data){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一��?
                    if(isShowLoading == false){
                        //當連續兩次都錯誤時則提示錯誤訊息並不再取得生產資訊
                        reload_time++;
                        if(reload_time<2){
                            $scope.plotItem = undefined;
                            checkLotInfo(callback, isShowLoading);
                        } else {
                            //$scope.$root.showAlert(data.Message, function(){
                            $scope.plotItem = undefined;
                            if(callback)
                                callback();
                            //});
                        }
                    } else {
                        $scope.$root.showAlert(data.Message);
                    }
                },
                netError: function(msg){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一��?
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(msg, isShowLoading, function(){
                        lotinfo_get(plotItem, callback, isShowLoading);
                    });
                }
            }, isShowLoading);
        }

        var displayLoginMin;
        function caclLoginMin(){
            if($scope.loginTime){
                displayLoginMin = $interval(function() {
                    var loginTime = moment($scope.loginTime);
                    var nowTime = moment(new Date());
                    $scope.loginMin = nowTime.diff(loginTime, 'minutes') ;
                }, 1000);
            }
        }

        var dog = {
            bark:function(feed, next){
                //使用user.infomation.get取得使用者資��?
                user_infomation_get(function(){
                    //使用favourite.machine.info.get取得我的最愛機��?
                    //取得設備加工資訊
                    favourite_machine_info_get(next, next == undefined);
                }, next == undefined);
            }
        };
/****SLight**************************************************/
        $scope.showSlight = function(){
            return $RouterExtendProvider.showSlight();
        };

        $scope.showSlightList = function(slight_type_no){
            //$scope.$root.loadSideSubMenu(undefined, {mode:'mailbox'});
            $RouterExtendProvider.showMailList(slight_type_no);
        };

        // 20231206 add by Alan for M#151347: 返回生產任務是否被選中
        $scope.checkSelect = function (item) {
            if ($scope.plotItem) {
                return ($scope.plotItem.plot_no == item.plot_no)
                    && ($scope.plotItem.op_no == item.op_no)
                    && ($scope.plotItem.status == item.status);
            } else {
                return false;
            }
        };

        $scope._event = {
            'machineList':{
                selectAll:()=>{
                    $scope._event['machineList'].isSelectAll = !$scope._event['machineList'].isSelectAll;
                    $scope.machineSelectAll();
                },
                checkSelect:(item)=>{
                    return $scope.machineItem.machine_no == item.machine_no;
                },
                click:(item, args)=>{
                    $scope.machineSelect(args.event, args.index,item);
                },
                checkClick:(item)=>{
                    return $scope.dashboard['machineStatusPlus'].machineStatus[item.machine_no].isSelect;
                },
                rowClick:(item, args)=>{
                    $scope.changeMachine(item);
                    if($scope.plotItem)
                        $scope.plotItem.open_scan_column = false; //把進出站的掃描欄位關掉
                    // 20231031 delete by Alan for M#148965: 移除未使用的程式碼，避免報錯
                }
            },
            'production_info_detail':{
                // 20231031 modify by Alan for M#148965: 增加預設值，避免報錯
                getPages:(list, PageConfig, filterItem = {}, orderItem)=>{
                    if(list){
                       // 20231121 modify by shiwl    0150629: 【乔登卫浴】作业区平台产品编号等栏位有设置上下标，但是不能排序
                       if(orderItem)
                       list =  $filter('orderBy')(list,orderItem.code,orderItem.order);
                        var temp_list = list.filter(function(item, index, array){
                            var isOK = true,
                                keys = Object.keys(filterItem);
                            for(var i =0; i<keys.length;i++){
                                var key = keys[i];
                                if(isOK && item[key]!=null && filterItem[key] && filterItem[key]!=''){
                                    if(item[key].indexOf(filterItem[key]) == -1){
                                        isOK = false;
                                        break;
                                    }
                                }
                            }
                            //狀態過��?
                            if(isOK && $scope.dashboard['workLog'].statusList.indexOf(item.status) ==-1){
                                isOK = false;
                            }
                            return isOK;
                        });
                        var orderCondition = genHeadOrderCondition(orderItem||{});
                        if(orderCondition && orderCondition.length > 0)
                            temp_list = $filter('orderBy')(temp_list, orderCondition);
                        if(PageConfig){
                            PageConfig.total_page = Math.ceil(temp_list.length/PageConfig.page_count)||1;
                            if(PageConfig.page >= PageConfig.total_page){
                                PageConfig.page = 0;
                            }
                            var index = PageConfig.page*PageConfig.page_count;
                            $scope.temp_list = temp_list;
                            $scope.plot_list = temp_list.slice(index, index+PageConfig.page_count)
                            return temp_list.slice(index, index+PageConfig.page_count);
                        } else {
                            $scope.temp_list = temp_list;
                            $scope.plot_list = temp_list;
                            return temp_list;
                        }
                    } else {
                        $scope.temp_list = list;
                        $scope.plot_list = list;
                        return list;
                    }
                },
                rowClick:(item, args)=>{
                    $scope.plotItem = item;
                    // 20210330 modify by 奕達 for M#90257
                    lotinfo_get(item, undefined, true);
                    $scope.workLogStatus = item.status;
                    var content = {
                        op_no: $scope.plotItem.op_no
                    };
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_MAT.check_plugIn',
                        content: content,
                        success: function (data) {
                            if (parseInt(data.qty, 10) >= 1) {
                                $scope.isPlugInEqualFive = true;
                            } else {
                                $scope.isPlugInEqualFive = false;
                            }
                        }
                    });
                    $scope.plotItem.open_scan_column = false; //把進出站的掃描欄位關掉
                    $scope._event['production_info_detail'].openBubbleList(item, args);
                },
                checkSelect: (item) => $scope.checkSelect(item)
            },
            'production_info_detail.double_unit_qty': {
                isShown: 'N'
            }
        }
        $scope._fn = {
            'production_info_detail.F0101':{ //物料管理
                isShown:(item, args)=>{ 
                    return (
                        ['Q','R','C','W'].includes(item.status)
                        && $scope.feedingOpionOn
                    )?'Y':'N';
                },
                click:(item, args)=>{
                    $mdDialog.serviceDialog(args.func.funcForm||'F0101Service', {
                        parent: 'B0214',
                        wo_no: $scope.plotItem.wo_no,
                        op_no: $scope.plotItem.op_no,
                        lot_no: $scope.plotItem.plot_no,//20210507 modify by 德義_林佳諺 for #0086310 檢查PlugIn需要之參數
                        machine_no: $scope.machineItem.machine_no,
                        check_dispatch_machine: $scope.machineItem.check_dispatch_machine,  // 20231103 modify by Alan for#0149409 : 是否為派工設備
                        callback : function(){
                            dog.bark();
                        }
                    });
                }
            },
            'production_info_detail.B0204':{//上料
                isShown:(item, args)=>{
                    return (
                        ['Q', 'R', 'W'].includes(item.status)
                        && ['0', '1'].includes($scope.machineItem.machine_status)
                        && !$scope.feedingOpionOn
                    )?'Y':'N';
                }, 
                click:(item, args)=>{
                    $mdDialog.serviceDialog(args.func.funcForm||'B0204Service', $scope.machineItem, $scope.plotItem, 'machine', function(){
                        dog.bark();
                    });
                }
            },
            'production_info_detail.Inject02':{//Recipe參數
                isShown:(item, args)=>{
                    return (
                        ['Q', 'R', 'W'].includes(item.status)
                        && ['0', '1'].includes($scope.machineItem.machine_status)
                        && $scope.IsInjectionMolding
                    )?'Y':'N';
                }, 
                click:(item, args)=>{
                    $mdDialog.serviceDialog(args.func.funcForm||'Inject02Service', $scope.machineItem, $scope.plotItem);
                }
            },
            'production_info_detail.B0230':{//標籤列印
                isShown:(item, args)=>['Q', 'R', 'W', 'C'].includes(item.status)?'Y':'N',
                click:(item, args)=>{
                    $mdDialog.serviceDialog(args.func.funcForm||'B0230Service', {plotItem:$scope.plotItem});
                }
            },
            'production_info_detail.B0205':{//進站報工
                isShown:(item, args)=>{
                    return (
                        ['Q', 'B'].includes(args.stauts||item.status)
                        && ['0', '1'].includes($scope.machineItem.machine_status)
                    )?'Y':'N';
                },
                click:(item, args)=>{
                    // 20231109 modify by Alan for#0150018: 出站报工界面和输入的生产批号不一样
                    $scope.plotItem = item;
                    //20220311 modify by 翰鴻 for M#102608
                    var content = {
                        EquipmentNo: $scope.machineItem.machine_no,
                        lotno: $scope.plotItem.plot_no
                    };
                    in_order_check(content, function () {
                        //M#95547 add by a991241234 找出生產批是否有 派工合併註記
                        plot_in_out_btn_action(
                        function () {
                            //sure action
                            var lot_check_in_batch_action = $filter("filter")(dialogList, { programName: "B0218" });
                            if (lot_check_in_batch_action && lot_check_in_batch_action.length > 0)
                                lot_check_in_batch_action[0].init();
                        },
                        function () {
                            // 20240216 modify by Alan for M#134708: 作業人員工作平台，當上工人員圖示為非打勾狀態，則無法進站報工
                            if (!$scope.onMachineUser($scope.machineItem)) {
                                $scope.$root.showAlert($filter('translate')('B0214.showAlert.no_online_operator'));
                                return;
                            }
                            
                            //cancel action
                            if (item.status == 'Q') {
                                $mdDialog.serviceDialog(args.func.funcForm||'B0205Service', $scope.machineItem, $scope.plotItem, 'machine', function () {
                                    dog.bark();
                                });
                            } else if (args.status == 'B') {//TODO 刷條碼
                                var plotInfo = angular.merge({}, $scope.plotItem);
                                $scope.$root.getService(args.func.funcForm||'B0205Service', function ($B0205Service) {
                                    $B0205Service.SMES_PlotCheckInProcess({
                                        machine_no: $scope.machineItem.machine_no,
                                        plotInfo: plotInfo,
                                        feedback: function () {
                                            dog.bark();
                                        }
                                    });
                                });
                            }
                        });
                    });
                }
            },
            'production_info_detail.B0206':{//出站報工
                isShown:(item, args)=>{
                    return (
                        ['R', 'B'].includes(args.stauts||item.status)
                        && ['0', '1'].includes($scope.machineItem.machine_status)
                    )?'Y':'N';
                },
                click:(item, args)=>{
                    // 20231109 modify by Alan for#0150018: 出站报工界面和输入的生产批号不一样
                    $scope.plotItem = item;
                    //M#95547 add by a991241234 找出生產批是否有 派工合併註記
                    plot_in_out_btn_action(function()
                    {
                        //sure action
                        var lot_check_out_batch_action =  $filter("filter")(dialogList,{programName:"B0219"});
                        if(lot_check_out_batch_action && lot_check_out_batch_action.length > 0)
                            lot_check_out_batch_action[0].init();
                    },function () 
                    {
                        //cancel action
                        var msg = '';
                        //20190422 modify by Dustdusk for M#56727: 根據AllowCheckOutWithOutOperator判斷出站是否需要有人在線上
                        //20211125 modify by Liuyang for M#99947:改为Y或1时检核
                        if(config.cache.sys_parameter.AllowCheckOutWithOutOperator == 'Y' || config.cache.sys_parameter.AllowCheckOutWithOutOperator == '1'){
                            if(!$scope.onMachineUser($scope.machineItem)){
                                msg = $filter('translate')('B0201.msg.no_online_operator');
                            }
                        }
                        if(msg == ''){
                            //20221012 add by 翰鴻 for M#118366
                            var proList = new Set();
                            $.each($scope.dashboard.workLog.production_info_detail, function (index, obj) {
                                if (obj.status == 'R' || obj.status == 'Q' || obj.status == 'W')
                                    proList.add(obj.item_no);
                            });
                            $mdDialog.serviceDialog(args.func.funcForm||'B0206Service', $scope.machineItem, $scope.plotItem, 'machine', 'B0214', function () {
                                dog.bark();
                            }, proList);
                        } else {
                            $scope.$root.showAlert(msg);
                        }
                    });
                }
            },
            'production_info_detail.B0234':{//工單模治具
                isShown:(item, args)=>{
                    return (
                        ['Q', 'R', 'W'].includes(item.status)
                        && ['0', '1'].includes($scope.machineItem.machine_status)
                        && $scope.IsInjectionMolding
                    )?'Y':'N';
                }, 
                click:(item, args)=>{
                    $mdDialog.serviceDialog(args.func.funcForm||'B0234Service', {
                        plotItem:$scope.plotItem,
                        feedback:function(){
                            dog.bark();
                        }
                    });
                }
            },
            'production_info_detail.B0218':{//批次進站
                isShown:(item, args)=>{
                    return (
                        ['Q'].includes(item.status)
                        && ['0', '1'].includes($scope.machineItem.machine_status)
                    )?'Y':'N';
                },
                click:(item, args)=>{
                    // 20200713 modify by WeiTing for M#74348: 把過濾後的狀態Q的生產批帶到批次進站裡做判斷。
                    $scope.temp_list = $scope.temp_list.filter(function(plotItem){
                        return plotItem.status === 'Q';
                    });
                    $mdDialog.serviceDialog(args.func.funcForm||'B0218Service',$scope.plotItem,$scope.machineItem.machine_no,$scope.workLogFilter.plot_no, 'B0214', $scope.temp_list, function(){
                        dog.bark();
                    });
                }
            },
            'production_info_detail.B0219':{//批次出站
                isShown:(item, args)=>{
                    return (
                        ['R'].includes(item.status)
                        && ['0', '1'].includes($scope.machineItem.machine_status)
                    )?'Y':'N';
                },
                click:(item, args)=>{
                    var msg = '';
                    //20190422 modify by Dustdusk for M#56727: 根據AllowCheckOutWithOutOperator判斷出站是否需要有人在線上
                    //20211125 modify by Liuyang for M#99947:改为Y或1时检核
                    if(config.cache.sys_parameter.AllowCheckOutWithOutOperator == 'Y' || config.cache.sys_parameter.AllowCheckOutWithOutOperator == '1'){
                        if(!$scope.onMachineUser($scope.machineItem)){
                            msg = $filter('translate')('B0201.msg.no_online_operator');
                        }
                    }
                    if(msg == ''){
                        // 20210427 modify by 14169 for M#91283: 把過濾後的狀態R的生產批帶到批次出站裡做判斷。
                        $scope.temp_list = $scope.temp_list.filter(function(plotItem){
                            return plotItem.status === 'R';
                        });
                        $mdDialog.serviceDialog(args.func.funcForm||'B0219Service', $scope.plotItem,$scope.machineItem.machine_no,$scope.workLogFilter.plot_no, 'B0214', $scope.temp_list, function(){
                            dog.bark();
                        });
                    } else {
                        $scope.$root.showAlert(msg);
                    }
                }
            },
            'production_info_detail.B0207-1':{//首件檢查
                isShown:(item, args)=>{  
                    return (
                        ['R', 'W'].includes(item.status)
                        && ['0', '1'].includes($scope.machineItem.machine_status)
                    )?'Y':'N';
                },
                click:(item, args)=>{
                    $mdDialog.serviceDialog(args.func.funcForm||'B0207Service', {
                        plotItem:$scope.plotItem,
                        machine_no:$scope.machineItem.machine_no,
                        area_no:'',
                        type: '0',
                        //20230322 modify by ShengKun for M# 121894: 序列號檢驗優化    
                        needsn: $scope.dashboard.productInfo.NeedSN,
                        // 20200110 modify by WeiTing for M#66287 - SPC檢驗須要多傳入品號��?
                        product_id:$scope.dashboard.productInfo.item_code,
                        feedback:function(){
                            dog.bark();
                        }
                    });
                }
            },
            'production_info_detail.B0207-2':{//巡檢
                isShown:(item, args)=>{  
                    return (
                        ['R', 'W'].includes(item.status)
                        && ['0', '1'].includes($scope.machineItem.machine_status)
                    )?'Y':'N';
                },click:(item, args)=>{
                    first_check_defect_qty(3,function(param){
                        var input_qty = param.input_qty;
                        var defect_qty = param.defect_qty;
                        if(input_qty > defect_qty){  
                            // 20230322 modify by alan for#130771: 巡檢type字段應為'2'
                            $mdDialog.serviceDialog(args.func.funcForm||'B0207Service', {
                                plotItem:$scope.plotItem,
                                machine_no:$scope.machineItem.machine_no,
                                area_no:'',
                                type: '1',
                                //20230613 add by Ruke for M#137443: [6.0.1Patch] [MSSQL]MES序列号检验问题
                                needsn: $scope.dashboard.productInfo.NeedSN,
                                // 20200110 modify by WeiTing for M#66287 - SPC檢驗須要多傳入品號��?
                                product_id:$scope.dashboard.productInfo.item_code,
                                queryNumber:param,
                                feedback:function(){
                                    dog.bark();
                                }
                            });
                        } else {
                              $scope.$root.showAlert($filter('translate')('B0214.msg.all_current_production_batches_are_inspected_as_defective_and_cannot_be_inspected_again'));
                        }
                    });
                }
            },
            'production_info_detail.B0240':{//自检
                isShown:(item, args)=>{  
                    return (
                        ['Q', 'R', 'W'].includes(item.status)
                        && ['0', '1'].includes($scope.machineItem.machine_status)
                    )?'Y':'N';
                },
                click:(item, args)=>{
                    // 20230322 modify by alan for#130771: 自检type字段應為'5'
                    $mdDialog.serviceDialog(args.func.funcForm||'B0240Service', {
                        plotItem: $scope.plotItem,
                        machine_no: $scope.machineItem.machine_no,
                        area_no: '',
                        type: '3',
                        //20230322 modify by ShengKun for M# 121894: 序列號檢驗優化
                        needsn: $scope.dashboard.productInfo.NeedSN,
                        // 20200110 modify by WeiTing for M#66287 - SPC檢驗須要多傳入品號��?
                        product_id: $scope.dashboard.productInfo.item_code,
                        feedback: function () {
                            dog.bark();
                        }
                    });
                }
            },
            'production_info_detail.B0241':{//末检    末檢4 
                isShown:(item, args)=>{  
                    return (
                        ['R', 'C'].includes(item.status)
                        && ['0', '1'].includes($scope.machineItem.machine_status)
                    )?'Y':'N';
                },
                click:(item, args)=>{
                    first_check_defect_qty(4,function(param){
                        // 20221130 modify by shiwl for M#122742 - 针对巡检、末检，如果已验不良数量（未出站）>=R状态数量，则不允许执行检验
                        var input_qty = param.input_qty;
                        var defect_qty = param.defect_qty;
                        if(input_qty > defect_qty){
                            // 20230322 modify by alan for#130771: 末检type字段應為'4'
                            $mdDialog.serviceDialog(args.func.funcForm||'B0241Service', {
                                    plotItem: $scope.plotItem,
                                    machine_no: $scope.machineItem.machine_no,
                                    area_no: '',
                                    type: '2',
                                    //20230322 modify by ShengKun for M# 121894: 序列號檢驗優化
                                    needsn: $scope.dashboard.productInfo.NeedSN,
                                    // 20200110 modify by WeiTing for M#66287 - SPC檢驗須要多傳入品號��?
                                    product_id: $scope.dashboard.productInfo.item_code,
                                    queryNumber:param,
                                    feedback: function () {
                                        dog.bark();
                                    }
                                });
                        }else {
                            $scope.$root.showAlert($filter('translate')('B0214.msg.all_current_production_batches_are_inspected_as_defective_and_cannot_be_inspected_again'));
                        }
                    });
                }
            },
            'production_info_detail.B0208':{//暫停
                isShown:(item, args)=>{
                    if('Q' == item.status && ['0', '1'].includes($scope.machineItem.machine_status)){
                        return 'Y';
                    } else if('R' == item.status){
                        return 'Y';
                    } else {
                        return 'N';
                    }
                },
                click:(item, args)=>{
                    $mdDialog.serviceDialog(args.func.funcForm||'B0208Service', {
                        machine_no: $scope.machineItem.machine_no,
                        plotItem: $scope.plotItem,
                        feedback: function(){
                               // 20240325 modify by wenwei for M#160267: [Oracle][H5][设备稼动]生产线工作平台-暂停后设备状态未变
                               dog.bark(undefined, function () {
                                var count = 0;
                                $scope.dashboard.workLog.production_info_detail.forEach(function (item) {
                                    if (item.status == 'R') {
                                        count++;
                                    }
                                });
                                if (count == 0) {//是否為最後一筆'R'
                                    //20240511 modify by wenlei for M#162444
                                    // machine_status == '0' 只有原设备状态=加工时，当前设备无加工中任务才需切换设备状态为闲置
                                    if($scope.machineItem.machine_status == '0'){
                                        changeMachineStatusProcess(content);
                                   } 
                                }
                            });
                        }
                    });
                }
            },
            'production_info_detail.B0209':{//解除暫停
                isShown:(item, args)=>['W'].includes(item.status)?'Y':'N',
                click:(item, args)=>{
                    $mdDialog.serviceDialog(args.func.funcForm||'B0209Service', {
                        machine_no: $scope.machineItem.machine_no,
                        plotItem: $scope.plotItem,
                        //20210628 modify by kaiinagami for M#87684 - 煩請協助更新讓步程式[龍畿]
                        //next_op_no參數獨立
                        next_op_no: $scope.next_op_no,
                        feedback: function(){
                            dog.bark(undefined, function () {
                                var count = 0;
                                $scope.dashboard.workLog.production_info_detail.forEach(function (item) {
                                    if (item.status == 'R') {
                                        count++;
                                    }
                                });
                                if (count > 0) {//当前设备有R状态任务
                                    //20240511 modify by wenlei for M#162444
                                    // machine_status == '1' 只有原设备状态=闲置时，当前设备有加工中任务才需切换设备状态为加工
                                    if($scope.machineItem.machine_status == '1'){
                                        changeMachineStatusProcess(content);
                                   } 
                                }
                            });
                        },
                        machineItem: $scope.machineItem
                    });
                }
            },
            'production_info_detail.B0212':{//ESOP
                isShown:(item, args)=>['Q','R','C','W','P'].includes(item.status)?'Y':'N',
                click:(item, args)=>{
                    $mdDialog.serviceDialog(args.func.funcForm||'B0212Service', $scope.plotItem);
                }
            },
            'production_info_detail.A0401':{//分批作業
                isShown:(item, args)=>{
                    if('Q' == item.status && ['0', '1'].includes($scope.machineItem.machine_status)){
                        return 'Y';
                    } else if('R' == item.status){
                        return 'Y';
                    } else {
                        return 'N';
                    }
                },
                click:(item, args)=>{
                    $mdDialog.serviceDialog(args.func.funcForm||'A0401Service', {
                        plotItem : $scope.plotItem,
                        feedback : function(){
                            dog.bark();
                        }
                    });
                }
            },
            'production_info_detail.A0402':{//併批作業
                isShown:(item, args)=>{
                    if('Q' == item.status && ['0', '1'].includes($scope.machineItem.machine_status)){
                        return 'Y';
                    } else if('R' == item.status){
                        return 'Y';
                    } else {
                        return 'N';
                    }
                },
                click:(item, args)=>{
                    $mdDialog.serviceDialog(args.func.funcForm||'A0402Service', {
                        plotItem : $scope.plotItem,
                        feedback : function(){
                            dog.bark();
                        }
                    });
                }
            },
            'production_info_detail.B0213':{//重工
                isShown:(item, args)=>{
                    if('Q' == item.status && ['0', '1'].includes($scope.machineItem.machine_status)){
                        return 'Y';
                    } else if('R' == item.status && ['0', '1', '3', '6', '7'].includes($scope.machineItem.machine_status)){
                        return 'Y';
                    } else {
                        return 'N';
                    }
                },
                click:(item, args)=>{
                    $mdDialog.serviceDialog(args.func.funcForm||'B0213Service', {
                        machine_no : $scope.machineItem.machine_no,
                        plot_detail : [$scope.plotItem],
                        feedback : function(){
                            dog.bark();
                        }
                    });
                }
            },
            'production_info_detail.B0223':{//產品變更
                isShown:(item, args)=>{
                    return (
                        ['Q', 'R', 'W', 'C'].includes(item.status)
                        && ['0', '1'].includes($scope.machineItem.machine_status)
                        && $scope.plotItem.product_change == '2'
                    )?'Y':'N';
                }, 
                click:(item, args)=>{
                    $mdDialog.serviceDialog(args.func.funcForm||'B0223Service', {
                        plotItem : $scope.plotItem,
                        feedback : function(){
                            dog.bark();
                        }
                    });
                }
            },
            'production_info_detail.B022502':{//報工還原
                isShown:(item, args)=>{
                    if('Q' == item.status && ['0', '1'].includes($scope.machineItem.machine_status)){
                        return 'Y';
                    } else if('R' == item.status){
                        return 'Y';
                    } else {
                        return 'N';
                    }
                },
                click:(item, args)=>{
                    $mdDialog.serviceDialog(args.func.funcForm||'B0225Service', {
                        machine_no : $scope.machineItem.machine_no,
                        plotItem : $scope.plotItem,
                        callback : function(){
                            dog.bark();
                        }
                    });
                }
            },
            'production_info_detail.B0226':{//設備變更
                isShown:(item, args)=>{
                    if('W' == item.status && ['0', '1'].includes($scope.machineItem.machine_status)){
                        return 'Y';
                    } else if('R' == item.status){
                        return 'Y';
                    } else {
                        return 'N';
                    }
                },
                click:(item, args)=>{
                    //20220822 modify by 翰鴻 for M#105814
                    var switch_plot_state;
                    if ($scope.workLogStatus == 'W')
                        switch_plot_state = 2;
                    else
                        switch_plot_state = 1;

                    $mdDialog.serviceDialog(args.func.funcForm||'B0226Service', {
                        machine_no : $scope.machineItem.machine_no,
                        plotItem: $scope.plotItem,
                        switch_plot_state: switch_plot_state,
                        callback : function(){
                            dog.bark();
                        }
                    });
                }
            },
            'production_info_detail.G0101':{//子作業
                isShown:(item, args)=>{
                    return (
                        ['Q','R','C','W'].includes(item.status)
                        && $scope.plotItem.have_subop
                    )?'Y':'N';
                },
                click:(item, args)=>{
                    $scope.$root.changeProgram(args.func.funcForm||'G0101', {data: {
                        plot_no: $scope.plotItem.plot_no,
                        op_no: $scope.plotItem.op_no,
                        op_name: $scope.plotItem.op_name
                    }});
                }
            },  // 20230802 modify by shiwl for M#0142184: [MSSQL][6.0][在线][工艺插件-热处理]工艺特性信息收集按钮未显示
            // 20230815 modify by shiwl  0142184: [MSSQL][6.0][在线][工艺插件-热处理]工艺特性信息收集按钮未显示
            'production_info_detail.B0237':{//工藝特性資訊收集
                isShown:(item, args)=>{
                    return (
                        ['Q', 'R', 'W'].includes(item.status)
                        && ['0', '1'].includes($scope.machineItem.machine_status)
                        && $scope.plotItem.op_plug_in == 1
                    )?'Y':'N';
                }, 
                click:(item, args)=>{
                    var heat_plot_no = '',
                    op_plug_in_detail = $scope.plotItem.op_plug_in_detail;
                    
                    // 判斷是否有爐批號
                    if(op_plug_in_detail && op_plug_in_detail.length > 0){
                        if(op_plug_in_detail[0].heat_plot_no && op_plug_in_detail[0].heat_plot_no !== ''){
                            heat_plot_no = op_plug_in_detail[0].heat_plot_no;
                        }
                    }

                    $mdDialog.serviceDialog(args.func.funcForm||'B0237Service', {
                        machine_no : $scope.machineItem.machine_no,
                        machine_name : $scope.machineItem.machine_name,
                        plot_no: $scope.plotItem.plot_no,
                        op_no: $scope.plotItem.op_no,
                        heat_plot_no: heat_plot_no,
                        callback : function(){
                            dog.bark();
                        }
                    });
                }
            },
            'production_info_detail.B0251':{//備刀提醒
                isShown:(item, args)=>{
                    return (
                        ['R'].includes(item.status)
                        && $scope.isPlugInEqualFive
                    )?'Y':'N';
                },
                click:(item, args)=>{
                    $mdDialog.serviceDialog(args.func.funcForm||'B0251Service', {
                        machine_no: $scope.machineItem.machine_no,
                        callback: function () {
                            dog.bark();
                        }
                    });
                }
            },
            'production_info_detail.B0252':{//換模提醒
                isShown:(item, args)=>{
                    return (
                        ['R'].includes(item.status)
                        && $scope.plotItem.op_plug_in == 3
                    )?'Y':'N';
                },
                click:(item, args)=>{
                    //改為開啟前先看有無資料
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_WIP.change_accessory_lotno_list_info_get',
                        content: {
                            EquipmentNo: $scope.machineItem.machine_no,
                            LOTNO: $scope.plotItem.plot_no
                        },
                        success: function (data) {
                            //20220506 modify 翰鴻 for M#110986
                            if (data.result != 0) {
                                if (data.result == 1) {
                                    $scope.$root.showAlert($filter('translate')('B0252.NotDispatch', { EquipmentNo: $scope.machineItem.machine_no }));
                                    return false;
                                }
                                else {
                                    //找不到step3生产批对应的模治具相关数据
                                    $scope.$root.showAlert($filter('translate')('B0252.NoAccessory'));
                                    return false;
                                }
                            }
                            else {
                                $mdDialog.serviceDialog(args.func.funcForm||'B0252Service', {
                                    AccessoryData: data.AccessoryData,
                                    callback: function () {
                                        dog.bark();
                                    }
                                });
                            }

                        }
                    });
                }
            }
        }
        function first_check_defect_qty(qc_type,callback){
            var content = {
                 machine_no:$scope.machineItem.machine_no,
                 op_no:$scope.plotItem.op_no,
                 plot_no:$scope.plotItem.plot_no,
                 qc_type:qc_type
            }
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_WIP.first_check_defect_qty',
                content: content,
                success: function (data) {
                    callback(data);
                }
            });
        }
        //M#95547 add by a991241234 生產批進出站優化(合併註記)
        function plot_in_out_btn_action(sure_call_back,cancel_call_back){
            //找出生產批是否有 派工合併註記
            //sure_call_back = 合併註記 confirm 確認 後執行 function
            //cancel_call_back = 合併註記 confirm 取消 或 尚未觸發 後執行 function
            if($scope.plotItem.batch_mark && $scope.plotItem.batch_mark.trim() != '')
            {
                var fliter_query = {};                                  //合併註記篩選條件
                fliter_query.batch_mark = $scope.plotItem.batch_mark;   //合併註記 tag
                fliter_query.op_no = $scope.plotItem.op_no;             //作業站
                fliter_query.status = $scope.plotItem.status;           //生產批狀態  
                var has_batch_mark_plot = $filter("filter")($scope.dashboard.workLog.production_info_detail,fliter_query);
                //判斷至少兩筆 才跳 confirm
                if(has_batch_mark_plot.length > 1)
                {
                    var msg = '';
                    var lot_note = has_batch_mark_plot.map(function(item)
                    {
                        return item.plot_no;
                    }).join("/");
                    if($scope.plotItem.status == "R")
                        msg = $filter('translate')('B0214.msg.lot_has_batch_mark_out',{batch_mark:$scope.plotItem.batch_mark,lot_note:lot_note});
                    else
                        msg = $filter('translate')('B0214.msg.lot_has_batch_mark_in',{batch_mark:$scope.plotItem.batch_mark,lot_note:lot_note});
                    $scope.$root.showConfirm(msg,
                    function(dialog_confirm){
                        //sure_action
                        dialog_confirm.hide();
                        if(typeof cancel_call_back === "function")
                            sure_call_back();
                    },
                    function(dialog_confirm){
                         //cancel_action
                        dialog_confirm.hide();
                        if(typeof cancel_call_back === "function")
                            cancel_call_back();
                    });
                }
                else
                {
                    //cancel_action
                    if(typeof cancel_call_back === "function")
                        cancel_call_back();
                }
            }
            else
            {
                //cancel_action
                if(typeof cancel_call_back === "function")
                    cancel_call_back();
            }
        }
/****Dashboard**************************************************************************************************************************************/
        $scope.dashboardPanel = ['operatorInfo','machineStatusPlus','workMaterial', 'productInfo', 'workLog', 'dashboard_info'];
        $scope.isInnerContentHide = false;

        $scope.togglePanel = function(sectionName, $event){
            var target = $scope.dashboard[sectionName];
            if(sectionName == 'workMaterial' || sectionName == 'workMaterialOp' || sectionName == 'productInfo' || sectionName == 'accessory' || sectionName == 'countInfo'){
                $scope.isInnerContentHide = !$scope.isInnerContentHide;
            } else if(sectionName == 'dashboard_info'){
                $scope.dashboard.dashboard_info.isForceHide = true;
                target.isContentHide = !target.isContentHide;
            } else {
                target.isContentHide = !target.isContentHide;
            }
        };

        //今日生產任務- C隱藏，R置頂
        var statusCount = 0;
        $scope.countStatus = function(item){
            if(item.status == 'C')
                statusCount++;
        };
        $scope.goStatusR = function(){
            $timeout(function(){
                var workLogList = document.getElementsByClassName('kmi-list__workLog')[0];
                //angular.element(document).find('.workLog .kmi-list__row-content');
                workLogList.scrollTop = (+statusCount)*46+2;
            });
        };

        /***
         * 機台狀態列��?
         * 0:RUN(加工) - ��?
         * 1:IDLE(閒置) - ��?
         * 2:DOWN(故障) - ��?
         * 3:SETUP(設置)
         * 4:SHUTDOWN(停機、關��?
         * 5:暫停(201609新增)
         * 6:維修(20190215新增)
         * 7:設置(20190215新增)
         **/
        $scope.machineStatus = function (status) {
            return 'status_'+status;
        };

        $scope.changeMachine = function(machine, callback){
            $scope.machineItem = machine;
            $scope.dashboard.machineStatusPlus.selectMachine = machine;
            $scope.machineItem.machine_no = machine.machine_no;
            //20170811 modify by Dustdusk for 清空選擇的plotItem
            $scope.plotItem = undefined;
            $scope.PageConfig.page = 0;
            $scope.dashboard.dashboard_info.isForceHide = false;
            machine_working_info_get('1011', callback);
            //20220923 add by 翰鴻 for M#118068
            //M#91613 切換設備時更新 IIoT 出站通知筆數
            if ($scope.IIoT_Enable) {
                get_eqp_prod_count(machine.machine_no, true, function (data) {
                    if (data.page_number_info_get && data.page_number_info_get.length > 0) {
                        $scope.plot_check_out_counter = data.page_number_info_get[0].cnt;
                    }
                });
            }
        };

        $scope.getPlotInfo = function(plot, event){
            event.stopPropagation();
            $scope.plotItem = plot;
            lotinfo_get(plot, undefined, true);
        };

        $scope.getDefectReason = function(plot, type){
            var reasonList = [];
            var defect_reason = '';

            //首:0, 巡:1, 自:2, 末:3
            //20210525 modify by kaiinagami for M#84490: 自/首/巡/末, 4種檢的不良現象分開存放 
            if(type == '0'){
                reasonList = plot.first_check_defect_reason || [];
            }
            else if (type == '1') {
                reasonList = plot.inspect_defect_reason || [];
            }
            else if (type == '2') {
                reasonList = plot.self_defect_reason || [];
            }
            else if (type == '3') {
                reasonList = plot.end_defect_reason || [];
            }

            // reasonList = [{reason_no: '' ,reason_name:'破損'},{reason_no: '' ,reason_name:'不美觀'},{reason_no: '' ,reason_name:'粗糙'}];
            if(reasonList.length > 0){
                reasonList.forEach(function(reason){
                    if(defect_reason != ''){
                        defect_reason = defect_reason + '<br>';
                    }
                    defect_reason = defect_reason + reason.reason_name;
                });
            }
            return defect_reason;
        }

        /***
        * 生產批物料是否投��?
        * 20170425新增，is_materials= 0 顯示紅色��? 顯示綠色 ��?1 不顯示顏��?
        * 20171113 mantis#0041868:調整，is_materials= 0 顯示紅色��? 顯示橘色��?綠色 ��?1 不顯示顏��?
        */
       $scope.isMaterials = function(is_materials){
            switch (is_materials){
                case '0':
                    return 'red';
                case '1':
                    return 'yellow';
                case '2':
                    return 'green';
            }
            return '';
       };

        $scope.loadMyFavorites = function(event){
            event.stopPropagation();
            $mdDialog.serviceDialog('PasswordService', {
                mode:'confirm',
                feedback:function(){
                    $WatchDogService.stopWatch();
                    $scope.$root.hideMenu();
                    $mdDialog.serviceDialog('B0214_FService', {
                        parent:'B0214',
                        next:'B0214',
                        master_no:config.cache.account,
                        machine_list:$scope.equipmentList,
                        feedback: function (dialog, data) {
                            dialog.hide();
                            //20190409 modify by Dustdusk for M#56387: 我的最愛快取造成設備列表錯誤
                            if (data.query_restult)
                                setMachineList(data.query_restult);
                            //$stateParams.machine_list = $scope.equipmentList;
                            $scope.plotItem = undefined;
                            dog.bark();
                        }
                    });
                }
            });
        };

        $scope.machineSelect = function(event, index,item){
            event.stopPropagation();
            var machine = $scope.dashboard.machineStatusPlus.machineStatus[item.machine_no];
            machine.isSelect = !machine.isSelect;
            //20210611 Modify by德義家興for#91011:
            $scope.options = item;
            dog.bark();
        };

        $scope.machineSelectAll = function(){
            $scope.dashboard.machineStatusPlus.selectAll = !$scope.dashboard.machineStatusPlus.selectAll;
            $scope.dashboard.machineStatusPlus.machineList.forEach(function(machine){
                $scope.dashboard.machineStatusPlus.machineStatus[machine.machine_no].isSelect = $scope.dashboard.machineStatusPlus.selectAll;
            });
        };

        //20210506 Modify by德義家興for#91011: [标准][DEV][行业议题]机加工-CNC-批量设备点检
        //將勾選到的設備放進selectedEquipmentList
        function setSelectedEquipmentList(){
            $scope.selectedEquipmentList = [];
            for(equipmentNo in $scope.dashboard.machineStatusPlus.machineStatus) {
                if ($scope.dashboard.machineStatusPlus.machineStatus[equipmentNo].isSelect == true) {
                    $scope.selectedEquipmentList.push(equipmentNo);
                }
            }
            //20210605 Modify by德義家興for#91011: 只勾選一個設備的時候 將勾選的設備的值給$scope.options 傳入B0210service
            if($scope.selectedEquipmentList.length == 1) { //只勾選一個設備
                var targetMachine = $scope.selectedEquipmentList[0]; //設定要找的設備編號
                for (i = 0; i < $scope.dashboard.machineStatusPlus.machineList.length; i++) { //在machineList裡面尋找
                    if ($scope.dashboard.machineStatusPlus.machineList[i].machine_no == targetMachine) {
                        $scope.options = $scope.dashboard.machineStatusPlus.machineList[i];
                        break;
                    }
                }
            }
            // 20230322 Modify by 文蔚 for M#123460: 如果勾选了则取勾选的设备，如果没有勾选则取选中的设备
            else if ($scope.selectedEquipmentList.length == 0) {
                for (i = 0; i < $scope.dashboard.machineStatusPlus.machineList.length; i++) { //在machineList裡面尋找
                    if ($scope.dashboard.machineStatusPlus.machineList[i].machine_no ==  $scope.dashboard.machineStatusPlus.selectMachine.machine_no) {
                        $scope.options = $scope.dashboard.machineStatusPlus.machineList[i];
                        break;
                    }
                }
            }
        };

        $scope.onMachineUser = function(machine){
            if(machine.employee_work_detail && machine.employee_work_detail.length > 0){
                // 20220928 modify by alan for#116249: 修正上下工異常顯示異常，過濾employee_no時未嚴格比對，$filter需傳入true參數
                var temp = $filter('filter')(machine.employee_work_detail, {employee_no:$scope.userInfo.employee_no}, true);
                machine.isWorkOn = (temp && temp.length > 0);
                return machine.isWorkOn;
            }
        };

        $scope.workSet = function(event, machine){
            event.stopPropagation();
            // 20210319 modify by 奕達 for M#89495, M#89785, M#89775 start
            $scope.changeMachine(machine, function(){
                has_lot_bind(machine.machine_no,function(data)
                {
                    if(data.page_number_info_get && data.page_number_info_get.length > 0)
                    {
                        var has_lot = data.page_number_info_get[0].lotbinding;
                        if(has_lot == "1")
                        {
                            if(machine.employee_work_detail.length === 0) {
                                lot_bind_mdDialog(machine, "U")
                            } else {
                                lot_bind_mdDialog(machine, "D")
                            }
                        } 
                        else
                        {
                            var work_mode = machine.isWorkOn?'D':'U';
                            var content = {
                                work_mode : work_mode,
                                employeewrokset : [{
                                    machine_no : machine.machine_no,
                                    machine_name : machine.machine_name,
                                    employee_no : $scope.userInfo.employee_no,
                                    work_mode : work_mode,
                                    work_datetime : new Date()
                                }],
                                need_check_skill:'0',//是否校驗
                                skill_check_result:'1',//校驗結果
                                skill_pass_user:''//驗證人員
                            };
                            if(!config.cache.permissions){
                                //全權��?
                                beforeEmpWorkSet(content, function(){
                                    employee_wrok_set_Imp(content);
                                });
                            } else{
                                // 20240419 modify by Alan for M#123460: 修正權限判斷
                                if(config.cache.permissions.indexOf(machine.isWorkOn?'B0203':'B0202')!=-1){
                                    beforeEmpWorkSet(content, function(){
                                        employee_wrok_set_Imp(content);
                                    });
                                } else {
                                    $scope.$root.showAlert($filter('translate')('common.msg.no_permissions'));
                                }
                            }
                        }
                    }
                });
            })
        };

        function lot_bind_mdDialog(machine, work_mode) {
            $mdDialog.serviceDialog('B0250Service',{
                mode_type: work_mode,
                lotInfoList:$scope.dashboard.workLog.production_info_detail,
                machineList: [machine],
                type: 'machine',
                parent: 'B0214'
            }, 
            function()
            {
                    dog.bark();
            });
        }
        // 20210319 modify by 奕達 for M#89495, M#89785, M#89775 end
        
        /*
        $scope.userInMachine = function(machine){
            var isWorkOn = '';
            if(machine.employee_work_detail.length > 0){
                for(var index in machine.employee_work_detail){
                    if(machine.employee_work_detail[index].employee_no == $scope.userInfo.employee_no){
                        isWorkOn = $filter('translate')('B0214.onWork');
                        machine.isWorkOn = true;
                        break;
                    }
                }
            }

            if(isWorkOn == ''){
                isWorkOn = $filter('translate')('B0214.nonWork');
                machine.isWorkOn = false;
            }

            return isWorkOn;
        }
        */

        // 是否需要人員上/下工原因��?. 上工 2. 下工 3. 皆需��?
        function isNeedWorkReason(work_mode){
            var result = false;

            if($scope.employeeWorkReason){
                if(work_mode == 'U' && $scope.employeeWorkReason == '1') {
                    result = true;
                } else if (work_mode == 'D' && $scope.employeeWorkReason == '2') {
                    result = true;
                } else if($scope.employeeWorkReason == '3'){
                    result = true;
                }
            }

            return result;
        }

        function beforeEmpWorkSet(content, callback){
            if(isNeedWorkReason(content.work_mode)){
                loadEmpWorkReason(content.work_mode, function(selectItem){
                    content.employeewrokset.forEach(function(item){
                        item.reason_no = selectItem.page_no;
                    });
                    if (callback)
                        callback();
                });
            } else {
                if (callback)
                    callback();
            }
        }

        // 人員原因基本資料取得
        function loadEmpWorkReason(work_mode, callback){
            var title = '';
            var query_condition_info = [{column_name:'ISSUESTATE', query_mode:'0', value:'2', merge_condition_model:'AND'}];

            if(work_mode == 'D'){ // 下工
                title = $filter('translate')('B0214.plz_select_offline_reason');
                query_condition_info.push({column_name:'REASONTYPE', query_mode:'0', value:'1', merge_condition_model:'AND' });
            } else if(work_mode == 'U'){ //上工
                title = $filter('translate')('B0214.plz_select_online_reason');
                query_condition_info.push({column_name:'REASONTYPE', query_mode:'0', value:'0', merge_condition_model:'AND' });
            }

            $MMWService.pageNumberInfoGet({
                page_mode : '35',
                query_condition_info: query_condition_info
            }, function(items){
                if(items && items.length > 0){
                    $scope.$root.showSelect({
                        label : function(item){
                            return item.page_name + '(' + item.page_no + ')';
                        },
                        title: title,
                        code : 'page_no',
                        selectCode : '',
                        list : items,
                        confirm : function(selectItem, radio_dialog){
                            radio_dialog.hide();
                            if (callback)
                                callback(selectItem);
                        }
                    });
                } else {
                    if(work_mode == 'D'){ // 下工
                        $scope.$root.showAlert($filter('translate')('B0214.showAlert.column8'));
                    } else if(work_mode == 'U'){ //上工
                        $scope.$root.showAlert($filter('translate')('B0214.showAlert.column7'));
                    }
                }
            });
        }

        function addWorkItem(work_mode, machine, employeewrokset){
            var msg = '';
            if(work_mode=='D' && !machine.isWorkOn){
                //當人員要下工 + 狀態為 未上��?> 錯誤
                //$scope.$root.showAlert('機台'+ machine.machine_no +'該人員已下工<br>');
                msg += $filter('translate')('B0214.msg.column1')+ machine.machine_no + $filter('translate')('B0214.msg.column2') + '<br>';
            } else if(work_mode=='U' && machine.isWorkOn){
                //當人員要上工 + 狀態為 已上��?> 錯誤
                //$scope.$root.showAlert('機台'+ machine.machine_no +'該人員已上工<br>');
                msg += $filter('translate')('B0214.msg.column1')+ machine.machine_no + $filter('translate')('B0214.msg.column3') + '<br>';
            } else {
                employeewrokset.push({
                    machine_no : machine.machine_no,
                    machine_name: machine.machine_name,
                    employee_no : $scope.userInfo.employee_no,
                    work_mode : work_mode,
                    work_datetime : new Date(),
                    reason_no: ''
                });
            }

            return msg;
        }

        //上工/下工
        function doWork(work_mode){
            //var isOnWork = checkOutWork($scope.machineItem.machine_no, data.employee_work_detail);
            var content = {
                work_mode : work_mode,
                employeewrokset : [],
                need_check_skill:'0',//是否校驗
                skill_check_result:'1',//校驗結果
                skill_pass_user:'',//驗證人員
            };
            var selectMachineCount = 0;
            var msg = '';
            //將人員跟勾選機台做結��?
            $scope.equipmentList.forEach(function(equipment){
                if($scope.dashboard.machineStatusPlus.machineStatus[equipment.machine_no].isSelect){
                    //檢查此機台是否能上下工，可以的話將資料加入content.employeewrokset
                    //不行的話則回傳錯誤訊��?
                    msg += addWorkItem(work_mode, equipment, content.employeewrokset);
                    selectMachineCount++;
                }
            });
            //當機台沒有勾選的情況，則使用目前選擇的機��?
            if(selectMachineCount == 0){
                msg += addWorkItem(work_mode, $scope.machineItem, content.employeewrokset);
            }
            //M#84747 不卡控上下工
            if(content.employeewrokset.length > 0)
            {
                beforeEmpWorkSet(content, function(){
                    employee_wrok_set_Imp(content);
                });
            }
            else
            {
                $scope.$root.showAlert(msg);
            }
            /*if(msg != ''){
                $scope.$root.showAlert(msg);
            } else {
                beforeEmpWorkSet(content, function(){
                    employee_wrok_set_Imp(content);
                });
            }*/
        }

        // 人員技能檢��?
        function inspectUserSkill(inspectInfo, feedback){
            if(inspectInfo.employeewrokset && inspectInfo.employeewrokset.length > 0){
                var machineInfo = inspectInfo.employeewrokset.shift();
                if(machineInfo.work_mode == 'U'){
                    $mdDialog.serviceDialog('B0231Service', {
                        parent: inspectInfo.parent,
                        machine_no: machineInfo.machine_no,
                        machine_name: machineInfo.machine_name,
                        position_no: machineInfo.position,
                        op_no: inspectInfo.op_no,
                        area_no: inspectInfo.area_no,
                        user_no: inspectInfo.user_no,
                        user_name: inspectInfo.user_name,
                        user_title: inspectInfo.user_title,
                        releaser_verified: inspectInfo.releaser_verified,
                        feedback: function(dialog){
                            if(dialog){
                                inspectInfo.releaser_verified = dialog.releaser_verified;
                                dialog.hide();
                            }
                            inspectUserSkill(inspectInfo, feedback);
                        },
                        req_check:function(info){ // 20231218 add by shiwl for M#0151498: 力邦合信，正式区。人员技能检核以后无记录写入数据库
                                need_check = true;
                                check_member = info.account;
                        }
                    });
                }else{
                    if(feedback)
                        feedback();
                }
            }else{
                if(feedback)
                    feedback();
            }
        }

        function employee_wrok_set_Imp(content){
            var inspectInfo = {
                parent: 'B0214',
                op_no: '',
                area_no: '',
                user_no: $scope.userInfo.employee_no,
                user_name: $scope.userInfo.employee_name,
                user_title: $scope.userInfo.user_title,
                releaser_verified: false,
                employeewrokset : angular.extend([], content.employeewrokset)
            }
            inspectUserSkill(inspectInfo, function(){
                employee_wrok_set(content);
            });
        }

        function employee_wrok_set(content){
            if(need_check){ // 20231218 add by shiwl for M#0151498: 力邦合信，正式区。人员技能检核以后无记录写入数据库
                content.employeewrokset[0].need_check_skill = '1';
                content.employeewrokset[0].skill_check_result = '0'
                content.employeewrokset[0].skill_pass_user = check_member;
           } else {
                content.employeewrokset[0].need_check_skill = '0';
                content.employeewrokset[0].skill_check_result = '1'  
                 content.employeewrokset[0].skill_pass_user = '';
          }
            //20180518 modify by 李栋 for mantis#0047068
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_SYS.employee_wrok_set_process',
                content : content,
                success : function(data){
                    if(content.work_mode == 'U'){
                        $scope.$root.showToast($filter('translate')('B0214.showAlert.column1'));
                        dog.bark();
                    } else if(content.work_mode == 'D'){
                        $scope.$root.showToast($filter('translate')('B0214.showAlert.column2'));
                        dog.bark();
                    }
                }
            });
        }

        // 20230303 modify by Alan for#: module_setting卡控
        $scope.changePanel = function(event, panelCode){
            event.stopPropagation();
            var panelList = [
                {panelCode : 'workMaterial', panelName: $filter('translate')('dashboard.workMaterial.title')},
                {panelCode : 'productInfo', panelName: $filter('translate')('dashboard.productInfo.title')},
                {panelCode : 'accessory', panelName: $filter('translate')('dashboard.accessory.title')}
            ];
            if($scope.feedingOpionOn){
                panelList.push({panelCode : 'workMaterialOp', panelName: $filter('translate')('dashboard.workMaterialOp.title')});
            }
            if($scope.ESI_CLD) {
                panelList.push({panelCode : 'countInfo', panelName: $filter('translate')('dashboard.countInfo.title')});
            }
            $scope.$root.showSelect({
                title : $filter('translate')('common.msg.plz_select'),
                label : 'panelName',
                code : 'panelCode',
                selectCode : panelCode,
                list : panelList,
                confirm : function(item, dialog){
                    var now_panel_index = $scope.dashboardPanel.indexOf(panelCode);
                    var select_panel_index = $scope.dashboardPanel.indexOf(item.panelCode);
                    //當為-1時表示選擇的不再列表內，則不用做交換
                    if(select_panel_index != -1){
                        $scope.dashboardPanel[select_panel_index] = panelCode;
                    }
                    $scope.dashboardPanel[now_panel_index] = item.panelCode;
                    localStorage.setItem(config.appName + '_B0214_panel', JSON.stringify($scope.dashboardPanel));
                    dialog.hide();
                }
            });

        };

        $scope.showMaintainOrder = function(){
            return true;
        }

        //20210511 Modify by德義家興for#84772
        //當有生產批合併後會出現'+'號 點擊秀出由哪幾個生產批合併
        $scope.getWorkLogDetail = function(item,event){
            // event.stopPropagation();
            //準備資料;特定生產批的
            $scope.workLogTemp.splice(0,$scope.workLogTemp.length);
            $scope.workLogDetail.forEach(function(plot){
                //20220913 modify by wangzy for 0118716: 出站报工数据目前仅按照产品的生产批号进行合并，
                //没有作业站维度，需要增加，和表头的作业站没有关联关系
                if (plot.lotno == item.plot_no && plot.opno == item.op_no) {
                    $scope.workLogTemp.push(plot);
                }
            })
            openDialogWorkLogDetail(item); 
        }
        //'+'號開窗
        function openDialogWorkLogDetail(item){
            $mdDialog.dialog(
                'module/moduleB/program/B02/B0201/WorkLogDetail.tmp.html',
                function(dialog){
                    return{
                        plot_no: item.plot_no,
                        op_name: item.op_name,
                        op_no: item.op_no,
                        qty: item.qty,
                        workLogTemp: $scope.workLogTemp,
                        back: function () {
                            dialog.hide();
                        },
                        confirm:function(){
                            dialog.hide();
                        }
                    }
                }
            )
        }
        //取得每日生產任務;當日同一生產批出站的次數
        function getPlotV_CONTS(item,machine_no){
            $MMWService.pageNumberInfoGet({
                page_mode: 'getPlotV_CONTS',
                query_condition_info: [
                    { column_name: 'LOTNO', query_mode: '0', value: item.plot_no, merge_condition_model: 'AND' },
                    { column_name: 'OPNO', query_mode: '0', value: item.op_no, merge_condition_model: 'AND' },
                    { column_name: 'EQUIPMENTNO', query_mode: '0', value: machine_no, merge_condition_model: 'AND' }
                ]
            }, function (data) {
                    item.v_conts = data[0].v_conts;
            });
        }
        //取得每日生產任務;已出站生產批的資訊
        function getWorkLogPlotDetail(machine_no){
            $MMWService.pageNumberInfoGet({
                page_mode:'get_workLog_plot_detail',
                query_condition_info:[
                    { column_name: 'A.EquipmentNo', query_mode: '0', value: machine_no, merge_condition_model: 'AND' }
                ]
            }, function (data){
                $scope.workLogDetail = data;
            });
        }

/**************************************************************************************************************************************************/
        //barcode輸入
        $scope.input_plot_no = function(barcode){
            $scope.judge_mode(barcode);
        };

        $scope.judge_mode=function(barcode){
            if (barcode.split('ORD_001_')[0] === "") {
                // ORD_001_設備編號
                $scope.step_mode = 1;
                $scope.ORD_directive = '';
                $scope.next_step($scope.step_mode, barcode);
            } else if (barcode == 'ORD_000_A001') {
                // ORD_000_A001 條碼上工
                $scope.step_mode = 2;
                $scope.ORD_directive = '';
                $scope.next_step($scope.step_mode);
            } else if (barcode == 'ORD_000_A002') {
                // ORD_000_A002 條碼下工
                $scope.step_mode = 3;
                $scope.ORD_directive = '';
                $scope.next_step($scope.step_mode);
            } else if (barcode == 'ORD_000_A003') {
                // ORD_000_A003 條碼進站
                $scope.step_mode = 4;
                $scope.ORD_directive = $filter('translate')('B0214.placeholder.step3');
            } else if (barcode == 'ORD_000_A004') {
                // ORD_000_A004 條碼出站
                $scope.step_mode = 5;
                $scope.ORD_directive = $filter('translate')('B0214.placeholder.step3');
            } else if (barcode == 'ORD_000_A009') {
                $scope.step_mode = 0;
                $scope.ORD_directive ='';
            } else {
                $scope.next_step($scope.step_mode,barcode)
            }
        }

        $scope.next_step=function(mode,barcode){
            if(mode === 0){
                input_plot_no_callback(barcode);
            }else if(mode === 1){//設備功能
                machineBarcode(barcode);
            }else if(mode === 2){//上工
                doWorkBarcode('U');
            }else if(mode === 3){//下工
                doWorkBarcode('D');
            }else if(mode === 4){//進站
                check_import_export_mode(mode,barcode);
            }else if(mode === 5){//出站
                check_import_export_mode(mode,barcode);
            }
        }

        //QRCode輸入
        $scope.qrcode_plot_no = function(){
            $scope.$root.OpenScanner({
                after : function(result){
                    $scope.judge_mode(result.text);
                },
                exception: function(){
                    //目前裝置無法使用相機
                    $scope.$root.showAlert($filter('translate')('B0214.showAlert.column3'));
                },
                orientation : 'landscape'
            });
        };

        $scope.openStatusFilter = function(){
            var statusList = [
                {display:$filter('translate')('dashboard.workLog.status.q'), code:'Q', isSelect:($scope.dashboard['workLog'].statusList.indexOf('Q')!=-1)},
                {display:$filter('translate')('dashboard.workLog.status.r'), code:'R', isSelect:($scope.dashboard['workLog'].statusList.indexOf('R')!=-1)},
                {display:$filter('translate')('dashboard.workLog.status.w'), code:'W', isSelect:($scope.dashboard['workLog'].statusList.indexOf('W')!=-1)},
                {display:$filter('translate')('dashboard.workLog.status.c'), code:'C', isSelect:($scope.dashboard['workLog'].statusList.indexOf('C')!=-1)},
                {display:$filter('translate')('dashboard.workLog.status.o'), code:'O', isSelect:($scope.dashboard['workLog'].statusList.indexOf('O')!=-1)},
                {display:$filter('translate')('dashboard.workLog.status.i'), code:'I', isSelect:($scope.dashboard['workLog'].statusList.indexOf('I')!=-1)}
            ];
            $scope.$root.showCheckList({
                label : 'display',
                code : 'code',
                order : '$index',
                list : statusList,
                confirm: function(checkList, dialog) {
                    var workLogstatusList = [];
                    statusList.forEach(function(status) {
                        if (status['isSelect']) {
                            workLogstatusList.push(status['code']);
                        }
                    })
                    if (workLogstatusList.length == 0) {
                        $scope.$root.showAlert($filter('translate')('common.abnormal_detail.msg.check_atLeast_one_condition'));
                    } else {
                        dialog.hide();
                        localStorage.setItem(config.appName + "_B0214_workLogStatusList", JSON.stringify(workLogstatusList));
                        $scope.dashboard['workLog'].statusList = [];
                        checkList.forEach(function(temp) {
                            if (temp.isSelect === true) {
                                $scope.dashboard['workLog'].statusList.push(temp.code);
                            }
                        });
                    }
                }
            });
        };

        function input_plot_no_callback(barcode_plot_no){
            //檢查輸入的對不對
            var temp_plot_array = barcode_plot_no.split(';');
            $scope.dashboard['workLog'].barcode_plot_no = '';
            //20210412 modify by 德義_林佳諺 for #0086675 : 生產批條碼自動進出站-後端取得parameter數值(start)
            var plotItems = {'Q':[], 'R':[], 'W':[]};
            var content = {
                parameter_no: 'LotScanAutoCheckInOut'
            };
            $MMWService.sendToServer({
                uri:'ServicesSTD.Module_SYS.parameter_info_get',
                content: content,
                success: function(data){
                    if (data.parameter_info_get_details[0].parameter_value == 1){
                        $scope.dashboard['workLog'].production_info_detail.forEach(function(production_info){
                            if(temp_plot_array.length == 2){
                                if(barcode_plot_no == (production_info.plot_no + ';' + production_info.op_no)){
                                    if(!plotItems[production_info.status])
                                        plotItems[production_info.status] = [];
                                    plotItems[production_info.status].push(production_info);
                                }
                            } else {
                                if(barcode_plot_no == production_info.plot_no){
                                    if(!plotItems[production_info.status])
                                        plotItems[production_info.status] = [];
                                    plotItems[production_info.status].push(production_info);
                                }
                            }
            
                        });
                        // 20220222 modify by Alan for#10437: 修正掃碼找不到生產批對應邏輯
                        if(plotItems['R'].length == 0 && plotItems['Q'].length == 0 && plotItems['W'].length == 0){
                            if(temp_plot_array.length == 2){
                                //刷入的生產批{{plot_no}}作業站{{op_no}}並不包含在今日生產任務內，請確定刷入的條碼與選擇的機台是否正確��?
                                $scope.$root.showAlert($filter('translate')('B0214.msg.lotlog_opno_without_barcode', {plot_no:temp_plot_array[0], op_no:temp_plot_array[1]}));
                            } else {
                                //刷入的生產批{{plot_no}}並不包含在今日生產任務內，請確定刷入的條碼與選擇的機台是否正確��?
                                $scope.$root.showAlert($filter('translate')('B0214.msg.lotlog_without_barcode', {plot_no:temp_plot_array[0]}));
                            }
                        } else {
                            //20210524 modify by 德義_林佳諺 for #0086675 : 生產批條碼自動進出站
                            if(plotItems['R'].length == 1 && plotItems['Q'].length == 1 && plotItems['W'].length == 0){
                                // 20231030 modify by Alan for M#148761: 氣泡選單傳入多筆資料
                                let plots = [];
                                plots.push(plotItems['R'][0])
                                plots.push(plotItems['Q'][0])
                                $scope._event['production_info_detail'].openBubbleList($scope.plotItem, {
                                    status:'B',
                                    plots: plots
                                });
                                //20210412 modify by 德義_林佳諺 for #0086675 : 生產批條碼自動進出站
                            } else if(plotItems['Q'].length == 1 && plotItems['W'].length == 0 && plotItems['R'].length == 0){
                                //只找到Q
                                //直接進站
                                $scope.plotItem = plotItems['Q'][0];
                                var plotInfo = angular.merge({}, $scope.plotItem);
            
                                // 20200731 modify by WeiTing for M#75817 - 修正在有派工數量的情況，條碼進站需判斷派工數量(dispatch_qty)和進站數量(qty)，哪個少就帶少的那個。
                                plotInfo.dispatch_qty = plotInfo.dispatch_qty || 0;
                                if(plotInfo.qty > plotInfo.dispatch_qty && plotInfo.dispatch_qty != 0){
                                    //派工數量少並且不為0則使用派工數量
                                    plotInfo.qty = plotInfo.dispatch_qty;
                                }
                                // //20210511 modify by 德義_林佳諺 for #0086675 : 生產批條碼自動進出站
                                // $mdDialog.serviceDialog('B0205Service', $scope.machineItem , $scope.plotItem, 'machine', function(){
                                //     dog.bark();
                                // });

                                // 20240216 modify by Alan for M#134708: 作業人員工作平台，當上工人員圖示為非打勾狀態，則無法進站報工
                                if (!$scope.onMachineUser($scope.machineItem)) {
                                    $scope.$root.showAlert($filter('translate')('B0214.showAlert.no_online_operator'));
                                    return;
                                }

                                $scope.$root.getService('B0205Service', function($B0205Service){
                                    $B0205Service.SMES_PlotCheckInProcess({
                                        machine_no:$scope.machineItem.machine_no,
                                        plotInfo : plotInfo,
                                        feedback : function(){
                                            dog.bark();
                                        }
                                    });
                                });
                                //20210412 modify by 德義_林佳諺 for #0086675 : 生產批條碼自動進出站
                            } else if(plotItems['R'].length == 1 && plotItems['W'].length == 0 && plotItems['Q'].length == 0){
                                //只找到R
                                $scope.plotItem = plotItems['R'][0];
                                var plotInfo = angular.merge({}, $scope.plotItem);
                                //20221012 add by 翰鴻 for M#118366
                                var proList = new Set();
                                $.each($scope.dashboard.workLog.production_info_detail, function (index, obj) {
                                    if (obj.status == 'R' || obj.status == 'Q' || obj.status == 'W')
                                        proList.add(obj.item_no);
                                });
                                $scope.$root.getService('B0206Service', function($B0206Service){
                                    $B0206Service.init($scope.machineItem, $scope.plotItem, 'machine', 'B0214', function(){
                                        dog.bark();
                                    }, proList);
                                });
                            } else {
                                //'生產��?XXXX 狀態不為Q/R無法進站或出��?
                                //$scope.$root.showAlert($filter('translate')('B0214.msg.cant_handle_barcode', {plot_no:temp_plot_array[1]}));
                                $scope.workLogFilterShow.plot_no = true;
                                $scope.workLogFilter.plot_no = temp_plot_array[0];
                                //20210412 modify by 德義_林佳諺 for #0086675 : 生產批條碼自動進出站
                                if(plotItems['Q'].length > 0){
                                    $scope.plotItem = plotItems['Q'][0];
                                    $scope._event['production_info_detail'].openBubbleList($scope.plotItem, {});
                                    //$scope.openToolBar(plotItems['Q'][(plotItems['Q'].length - 1)].status);
                                }else if(plotItems['R'].length > 0){
                                    $scope.plotItem = plotItems['R'][0];
                                    $scope._event['production_info_detail'].openBubbleList($scope.plotItem, {});
                                    //$scope.openToolBar(plotItems['R'][(plotItems['R'].length - 1)].status);
                                }else if(plotItems['W'].length > 0){
                                    $scope.plotItem = plotItems['W'][0];
                                    $scope._event['production_info_detail'].openBubbleList($scope.plotItem, {});
                                    //$scope.openToolBar(plotItems['W'][(plotItems['W'].length - 1)].status);
                                }
                            }
                        }
                    }else{
                        $scope.workLogFilterShow.plot_no = true;
                        $scope.workLogFilter.plot_no = temp_plot_array[0];
                    }
                },
                error: function(e){
                    console.log('error_message', e);
                }
            });
            //20210412 modify by 德義_林佳諺 for #0086675 : 生產批條碼自動進出站-後端取得parameter數值(end)
        }
        //將排序物件轉成排序條件陣��?
        function genHeadOrderCondition(orderItem){
            var orderArray = [];
            var keys = Object.keys(orderItem);
            for(var i = 0; i<keys.length;i++){
                var key = keys[i];
                var prefix = (orderItem[key].order) ? '+' : '-';
                orderArray.push(prefix + key);
            }
            return orderArray;
        }

        $scope.clickHeadOrder = function(id){
            if(id == 'is_urgent'){
                if(!$scope.workLogOrder[id]){
                    $scope.workLogOrder = {
                        is_urgent : {order : false},
                        plot_no: {order: true},
                        op_no: {order: true}
                    }
                } else {
                    $scope.workLogOrder = {};
                }
            } else {
                if(!$scope.workLogOrder[id]){
                    // 尚未加入排序
                    $scope.workLogOrder[id] = {order: true};
                } else {
                    if($scope.workLogOrder[id].order){
                        // 若已正向排序 -> 改為反向排序
                        $scope.workLogOrder[id].order = false;
                    } else {
                        // 若已反向排序 -> 刪除此欄位的排序
                        delete $scope.workLogOrder[id];
                    }
                }
            }
        }

        /****************************以下為使用條碼刷入功能**************************************** */

        // 條碼切換設備
        function machineBarcode(barcode) {
            var machine_barcode = barcode.split('ORD_001_')[1],
                machine_list = $scope.dashboard['machineStatusPlus'].machineList,
                isMachineMatch = false;

            for (var i = 0; i < machine_list.length; i++) {
                if(machine_list[i].machine_no === machine_barcode){
                    isMachineMatch = true;
                    $scope.changeMachine(machine_list[i]);
                }
            }

            if(!isMachineMatch){
                // 查無此設備
                $scope.$root.showAlert($filter('translate')('B0214.barcode_msg.column1'));
            }
        }

        // 條碼上下工
        function doWorkBarcode(work_mode) {
            var content = {
                work_mode : work_mode,
                employeewrokset : []
        
            };
            var selectMachineCount = 0;
            var msg = '';
            //將人員跟勾選機台做結合
            $scope.equipmentList.forEach(function(equipment){
                if($scope.dashboard.machineStatusPlus.machineStatus[equipment.machine_no].isSelect){
                    //檢查此機台是否能上下工，可以的話將資料加入content.employeewrokset
                    //不行的話則回傳錯誤訊息
                    msg += addWorkItem(work_mode, equipment, content.employeewrokset);
                    selectMachineCount++;
                }
            });
            //當機台沒有勾選的情況，則使用目前選擇的機台
            if(selectMachineCount == 0){
                msg += addWorkItem(work_mode, $scope.machineItem, content.employeewrokset);
            }

            if(msg != ''){
                $scope.$root.showAlert(msg);
            } else {
                beforeEmpWorkSetBarcode(content, function(){
                    employee_wrok_set_Imp(content);
                });
            }
        }

        function beforeEmpWorkSetBarcode(content, callback){
            if(isNeedWorkReason(content.work_mode)){
                doWorkReasonDialog(content.work_mode, function(doWorkReason){
                    content.employeewrokset.forEach(function(item){
                        item.reason_no = doWorkReason;
                    });
                    if (callback)
                        callback();
                });
            } else {
                if (callback)
                    callback();
            }
        }

        // 條碼輸入上下工原因開窗
        function doWorkReasonDialog(work_mode, callback) {
            var title = '';

            if(work_mode == 'U') { //上工 (U)
                title = $filter('translate')('B0214.plz_select_online_reason');
            } else { // 下工 (D)
                title = $filter('translate')('B0214.plz_select_offline_reason');
            }

            $timeout(function() {
                if(document.activeElement.tagName != 'INPUT') {
                    document.getElementById("doWorkReason").focus();
                }
            });

            $mdDialog.dialog(
                'module/moduleB/program/barcode/doWorkReason.tmp.html',
                function (dialog) {
                    return {
                        title: title,
                        doWorkReason: '',
                        back: function() {
                            dialog.hide();
                        },
                        input_do_work_reason: function(event) {
                            if(event.keyCode === 13) {
                                dialog.input_do_work_reason_callback();
                            }
                        },
                        qrcode_do_work_reason: function() {
                            $scope.$root.OpenScanner({
                                after : function(result){
                                    dialog.input_do_work_reason_callback(result.text);
                                },
                                exception: function(){
                                    //目前裝置無法使用相機
                                    $scope.$root.showAlert($filter('translate')('B0214.showAlert.column3'));
                                },
                                orientation : 'landscape'
                            });
                        },
                        input_do_work_reason_callback: function() {
                            if (dialog.doWorkReason === 'ORD_000_A009'){
                                // ORD_000_A009 關閉按鈕
                                dialog.hide();
                            } else {
                                loadEmpWorkReasonBarcode(work_mode, dialog.doWorkReason, dialog, function(doWorkReason){
                                    dialog.hide();
                                    if(callback)
                                        callback(doWorkReason);
                                });
                            }
                        }
                    }
                }
            );
        }

        // 判斷刷入的上下工原因是否存在
        function loadEmpWorkReasonBarcode(work_mode, barcode, dialog, callback){
            var query_condition_info = [{column_name:'ISSUESTATE', query_mode:'0', value:'2', merge_condition_model:'AND'}];

            if(work_mode == 'D'){ // 下工
                query_condition_info.push({column_name:'REASONTYPE', query_mode:'0', value:'1', merge_condition_model:'AND' });
            } else if(work_mode == 'U'){ //上工
                query_condition_info.push({column_name:'REASONTYPE', query_mode:'0', value:'0', merge_condition_model:'AND' });
            }

            $MMWService.pageNumberInfoGet({
                page_mode : '35',
                query_condition_info: query_condition_info
            }, function(items){
                if(items && items.length > 0){
                    var isReasonMatch = false;
                    for (var i = 0; i < items.length; i++) {
                        if(items[i].page_no === barcode) {
                            isReasonMatch = true;
                            if(callback)
                                callback(items[i].page_no);
                            break;
                        }
                    }
                    if(!isReasonMatch) {
                        dialog.doWorkReason = '';
                        if (work_mode == 'D') { // 下工
                            // 查無此上工原因
                            $scope.$root.showAlert($filter('translate')('B0214.barcode_msg.column3'));
                        } else if(work_mode == 'U'){ //上工
                            // 查無此下工原因
                            $scope.$root.showAlert($filter('translate')('B0214.barcode_msg.column2'));
                        } 
                    }
                } else {
                    dialog.doWorkReason = '';
                    if(work_mode == 'D'){ // 下工
                        $scope.$root.showAlert($filter('translate')('B0214.showAlert.column8'));
                    } else if(work_mode == 'U'){ //上工
                        $scope.$root.showAlert($filter('translate')('B0214.showAlert.column7'));
                    }
                }
            });
        }
        //進出站開窗 add by Oliver for M#73832
        function open_export_outport_dialog(mode_num,plot_status,barcode){//進出站開窗
            $scope.plot_list=$scope.plot_list.filter(function(plotItem){
                return plotItem.status === plot_status;
            })
            let check_plot=false;
            $scope.plot_list.forEach(function(item){
                if(item.plot_no == barcode){
                    check_plot=true;
                    $scope.plotItem = item;
                    $scope.plotItem.open_scan_column=true;
                };
            });

            if(!check_plot){
                $scope.$root.showAlert($filter('translate')('B0214.showAlert.column9'));
                return
            }
            dialogList[mode_num].init(plot_status);
        }

        //檢查進出站mode add by Oliver for M#73832
        function check_import_export_mode(mode_num,barcode){
            if(mode_num===4){//進站
                if(dialogList[mode_num].programName==='B0205'){
                    open_export_outport_dialog(mode_num,'Q',barcode);
                }else{
                    let import_mode;
                    dialogList.forEach(function(item,key){
                        if(item.programName==='B0205'){
                            import_mode=key;
                        }
                    });
                    open_export_outport_dialog(import_mode,'Q',barcode);
                }
            }else if(mode_num===5){//出站
                if(dialogList[mode_num].programName==='B0206'){
                    open_export_outport_dialog(mode_num,'R',barcode);
                }else{
                    let export_mode;
                    dialogList.forEach(function(item,key){
                        if(item.programName==='B0206'){
                            export_mode=key;
                        }
                    });
                    open_export_outport_dialog(export_mode,'R',barcode);
                }
            }
        }
        
        // 20211101 modify by Alan for #93040 : [成綸企業][優化]sMES整合QMS卡控出站檢，拋檢驗單時於生產任務面板增加檢驗單號及推送時間欄位
        // 增加送驗時間欄位排序功能
        $scope.reverse = false;
        $scope.orderColumn = '';
        $scope.OrderChange = function (columnName) {
            if ($scope.orderColumn == columnName) {
                $scope.reverse = !$scope.reverse;
            } else {
                $scope.orderColumn = columnName;
                $scope.reverse = false;
            }
        };
    }
];});
